| 1 | import { exec } from "child_process"; |
| 2 | import path from "path"; |
| 3 | import { promisify } from "util"; |
| 4 | |
| 5 | import chalk from "chalk"; |
| 6 | import express, { Request, Response } from "express"; |
| 7 | import type { ChatCompletionMessageParam } from "openai/resources.mjs"; |
| 8 | |
| 9 | import { getAssistantSlug } from "../auth/workos.js"; |
| 10 | import { processCommandFlags } from "../flags/flagProcessor.js"; |
| 11 | import { toolPermissionManager } from "../permissions/permissionManager.js"; |
| 12 | import { |
| 13 | getService, |
| 14 | initializeServices, |
| 15 | SERVICE_NAMES, |
| 16 | } from "../services/index.js"; |
| 17 | import { |
| 18 | AuthServiceState, |
| 19 | ConfigServiceState, |
| 20 | ModelServiceState, |
| 21 | } from "../services/types.js"; |
| 22 | import { saveSession } from "../session.js"; |
| 23 | import { streamChatResponse } from "../streamChatResponse.js"; |
| 24 | import { StreamCallbacks } from "../streamChatResponse.types.js"; |
| 25 | import { constructSystemMessage } from "../systemMessage.js"; |
| 26 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 27 | import { getToolDisplayName } from "../tools/index.js"; |
| 28 | import { DisplayMessage } from "../ui/types.js"; |
| 29 | import { formatError } from "../util/formatError.js"; |
| 30 | import { logger } from "../util/logger.js"; |
| 31 | import { readStdinSync } from "../util/stdin.js"; |
| 32 | |
| 33 | import { ExtendedCommandOptions } from "./BaseCommandOptions.js"; |
| 34 | |
| 35 | const execAsync = promisify(exec); |
| 36 | |
| 37 | interface ServeOptions extends ExtendedCommandOptions { |
| 38 | timeout?: string; |
| 39 | port?: string; |
| 40 | org?: string; |
| 41 | } |
| 42 | |
| 43 | interface PendingPermission { |
| 44 | toolName: string; |
| 45 | toolArgs: any; |
| 46 | requestId: string; |
| 47 | timestamp: number; |
| 48 | } |
| 49 | |
| 50 | interface ServerState { |
| 51 | chatHistory: ChatCompletionMessageParam[]; |
| 52 | displayMessages: DisplayMessage[]; // Messages formatted for display with tool info |
| 53 | config: any; |
| 54 | model: any; |
| 55 | isProcessing: boolean; |
| 56 | lastActivity: number; |
| 57 | messageQueue: string[]; |
| 58 | currentAbortController: AbortController | null; |
| 59 | shouldInterrupt: boolean; |
| 60 | serverRunning: boolean; |
| 61 | pendingPermission: PendingPermission | null; |
| 62 | } |
| 63 | |
| 64 | export async function serve(prompt?: string, options: ServeOptions = {}) { |
| 65 | // Check if prompt should come from stdin instead of parameter |
| 66 | let actualPrompt = prompt; |
| 67 | if (!prompt) { |
| 68 | // Try to read from stdin (for piped input like: cat file | cn serve) |
| 69 | const stdinInput = readStdinSync(); |
| 70 | if (stdinInput) { |
| 71 | actualPrompt = stdinInput; |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | const timeoutSeconds = parseInt(options.timeout || "300", 10); |
| 76 | const timeoutMs = timeoutSeconds * 1000; |
| 77 | const port = parseInt(options.port || "8000", 10); |
| 78 | |
| 79 | // Initialize services with tool permission overrides |
| 80 | const { permissionOverrides } = processCommandFlags(options); |
| 81 | |
| 82 | await initializeServices({ |
| 83 | toolPermissionOverrides: permissionOverrides, |
| 84 | configPath: options.config, |
| 85 | rules: options.rule, |
| 86 | organizationSlug: options.org, |
| 87 | headless: true, // Skip onboarding in serve mode |
| 88 | }); |
| 89 | |
| 90 | // Get initialized services from the service container |
| 91 | const [configState, modelState] = await Promise.all([ |
| 92 | getService<ConfigServiceState>(SERVICE_NAMES.CONFIG), |
| 93 | getService<ModelServiceState>(SERVICE_NAMES.MODEL), |
| 94 | ]); |
| 95 | |
| 96 | if (!configState.config || !modelState.llmApi || !modelState.model) { |
| 97 | throw new Error("Failed to initialize required services"); |
| 98 | } |
| 99 | |
| 100 | const { config, llmApi, model } = { |
| 101 | config: configState.config, |
| 102 | llmApi: modelState.llmApi, |
| 103 | model: modelState.model, |
| 104 | }; |
| 105 | |
| 106 | // Organization selection is already handled in initializeServices |
| 107 | const authState = await getService<AuthServiceState>(SERVICE_NAMES.AUTH); |
| 108 | if (authState.organizationId) { |
| 109 | telemetryService.updateOrganization(authState.organizationId); |
| 110 | } |
| 111 | |
| 112 | // Log configuration information |
| 113 | const organizationId = authState.organizationId || "personal"; |
| 114 | const assistantName = config.name; |
| 115 | const assistantSlug = getAssistantSlug(authState.authConfig); |
| 116 | const modelProvider = model.provider; |
| 117 | const modelName = model.model; |
| 118 | |
| 119 | console.log(chalk.blue(`\nConfiguration:`)); |
| 120 | console.log(chalk.dim(` Organization: ${organizationId}`)); |
| 121 | console.log( |
| 122 | chalk.dim( |
| 123 | ` Assistant: ${assistantName}${ |
| 124 | assistantSlug ? ` (${assistantSlug})` : "" |
| 125 | }`, |
| 126 | ), |
| 127 | ); |
| 128 | console.log(chalk.dim(` Model: ${modelProvider}/${modelName}`)); |
| 129 | if (options.config) { |
| 130 | console.log(chalk.dim(` Config file: ${options.config}`)); |
| 131 | } |
| 132 | |
| 133 | // Initialize chat history |
| 134 | const chatHistory: ChatCompletionMessageParam[] = []; |
| 135 | const systemMessage = await constructSystemMessage( |
| 136 | options.rule, |
| 137 | undefined, |
| 138 | true, |
| 139 | ); |
| 140 | if (systemMessage) { |
| 141 | chatHistory.push({ role: "system", content: systemMessage }); |
| 142 | } |
| 143 | |
| 144 | // Initialize server state |
| 145 | const state: ServerState = { |
| 146 | chatHistory, |
| 147 | displayMessages: [], // Initialize empty display messages |
| 148 | config, |
| 149 | model, |
| 150 | isProcessing: false, |
| 151 | lastActivity: Date.now(), |
| 152 | messageQueue: [], |
| 153 | currentAbortController: null, |
| 154 | shouldInterrupt: false, |
| 155 | serverRunning: true, |
| 156 | pendingPermission: null, |
| 157 | }; |
| 158 | |
| 159 | // Record session start |
| 160 | telemetryService.recordSessionStart(); |
| 161 | telemetryService.startActiveTime(); |
| 162 | |
| 163 | const app = express(); |
| 164 | app.use(express.json()); |
| 165 | |
| 166 | // GET /state - Return the current state |
| 167 | app.get("/state", (_req: Request, res: Response) => { |
| 168 | state.lastActivity = Date.now(); |
| 169 | res.json({ |
| 170 | chatHistory: state.displayMessages, // Send display messages with proper formatting |
| 171 | isProcessing: state.isProcessing, |
| 172 | messageQueueLength: state.messageQueue.length, |
| 173 | pendingPermission: state.pendingPermission, |
| 174 | }); |
| 175 | }); |
| 176 | |
| 177 | // POST /message - Queue a message and potentially interrupt |
| 178 | app.post("/message", async (req: Request, res: Response) => { |
| 179 | state.lastActivity = Date.now(); |
| 180 | |
| 181 | const { message } = req.body; |
| 182 | if (!message) { |
| 183 | return res.status(400).json({ error: "Message field is required" }); |
| 184 | } |
| 185 | |
| 186 | // Queue the message |
| 187 | state.messageQueue.push(message); |
| 188 | |
| 189 | // If currently processing, set interrupt flag |
| 190 | if (state.isProcessing && state.currentAbortController) { |
| 191 | state.shouldInterrupt = true; |
| 192 | } |
| 193 | |
| 194 | res.json({ |
| 195 | queued: true, |
| 196 | position: state.messageQueue.length, |
| 197 | willInterrupt: state.shouldInterrupt, |
| 198 | }); |
| 199 | |
| 200 | // Process messages if not already processing |
| 201 | if (!state.isProcessing) { |
| 202 | processMessages(state, llmApi); |
| 203 | } |
| 204 | }); |
| 205 | |
| 206 | // POST /permission - Approve or reject pending tool permission |
| 207 | app.post("/permission", async (req: Request, res: Response) => { |
| 208 | state.lastActivity = Date.now(); |
| 209 | |
| 210 | const { requestId, approved } = req.body; |
| 211 | |
| 212 | if (!state.pendingPermission) { |
| 213 | return res.status(400).json({ error: "No pending permission request" }); |
| 214 | } |
| 215 | |
| 216 | if (state.pendingPermission.requestId !== requestId) { |
| 217 | return res.status(400).json({ error: "Invalid request ID" }); |
| 218 | } |
| 219 | |
| 220 | // Remove the permission request message |
| 221 | const lastMsg = state.displayMessages[state.displayMessages.length - 1]; |
| 222 | if (lastMsg && lastMsg.messageType === "tool-permission-request") { |
| 223 | state.displayMessages.pop(); |
| 224 | } |
| 225 | |
| 226 | // Send the permission response to the toolPermissionManager |
| 227 | if (approved) { |
| 228 | toolPermissionManager.approveRequest(requestId); |
| 229 | } else { |
| 230 | toolPermissionManager.rejectRequest(requestId); |
| 231 | } |
| 232 | |
| 233 | // Clear pending permission state |
| 234 | state.pendingPermission = null; |
| 235 | |
| 236 | res.json({ |
| 237 | success: true, |
| 238 | approved, |
| 239 | }); |
| 240 | }); |
| 241 | |
| 242 | // GET /diff - Return git diff against main branch |
| 243 | app.get("/diff", async (_req: Request, res: Response) => { |
| 244 | state.lastActivity = Date.now(); |
| 245 | |
| 246 | try { |
| 247 | // First check if we're in a git repository |
| 248 | await execAsync("git rev-parse --git-dir"); |
| 249 | |
| 250 | // Get the diff against main branch |
| 251 | const { stdout } = await execAsync("git diff main"); |
| 252 | |
| 253 | res.json({ |
| 254 | diff: stdout, |
| 255 | }); |
| 256 | } catch (error: any) { |
| 257 | // Git diff returns exit code 1 when there are differences, which is normal |
| 258 | if (error.code === 1 && error.stdout) { |
| 259 | res.json({ |
| 260 | diff: error.stdout, |
| 261 | }); |
| 262 | } else if (error.code === 128) { |
| 263 | // Handle case where we're not in a git repo or main branch doesn't exist |
| 264 | res.status(404).json({ |
| 265 | error: "Not in a git repository or main branch doesn't exist", |
| 266 | diff: "", |
| 267 | }); |
| 268 | } else { |
| 269 | logger.error(`Git diff error: ${formatError(error)}`); |
| 270 | res.status(500).json({ |
| 271 | error: `Failed to get git diff: ${formatError(error)}`, |
| 272 | diff: "", |
| 273 | }); |
| 274 | } |
| 275 | } |
| 276 | }); |
| 277 | |
| 278 | // Track intervals for cleanup |
| 279 | let inactivityChecker: NodeJS.Timeout | null = null; |
| 280 | |
| 281 | // POST /exit - Gracefully shut down the server |
| 282 | app.post("/exit", async (_req: Request, res: Response) => { |
| 283 | console.log( |
| 284 | chalk.yellow("\nReceived exit request, shutting down server..."), |
| 285 | ); |
| 286 | |
| 287 | // Respond immediately before shutting down |
| 288 | res.json({ |
| 289 | message: "Server shutting down", |
| 290 | success: true, |
| 291 | }); |
| 292 | |
| 293 | // Set server running flag to false to stop processing |
| 294 | state.serverRunning = false; |
| 295 | |
| 296 | // Abort any current processing |
| 297 | if (state.currentAbortController) { |
| 298 | state.currentAbortController.abort(); |
| 299 | } |
| 300 | |
| 301 | // Clear the message queue |
| 302 | state.messageQueue = []; |
| 303 | |
| 304 | // Clean up intervals |
| 305 | if (inactivityChecker) { |
| 306 | clearInterval(inactivityChecker); |
| 307 | inactivityChecker = null; |
| 308 | } |
| 309 | |
| 310 | // Give a moment for the response to be sent |
| 311 | setTimeout(() => { |
| 312 | server.close(() => { |
| 313 | telemetryService.stopActiveTime(); |
| 314 | process.exit(0); |
| 315 | }); |
| 316 | }, 100); |
| 317 | }); |
| 318 | |
| 319 | const server = app.listen(port, () => { |
| 320 | console.log(chalk.green(`Server started on http://localhost:${port}`)); |
| 321 | console.log(chalk.dim("Endpoints:")); |
| 322 | console.log(chalk.dim(" GET /state - Get current agent state")); |
| 323 | console.log( |
| 324 | chalk.dim( |
| 325 | " POST /message - Send a message (body: { message: string })", |
| 326 | ), |
| 327 | ); |
| 328 | console.log( |
| 329 | chalk.dim( |
| 330 | " POST /permission - Approve/reject tool (body: { requestId, approved })", |
| 331 | ), |
| 332 | ); |
| 333 | console.log( |
| 334 | chalk.dim(" GET /diff - Get git diff against main branch"), |
| 335 | ); |
| 336 | console.log( |
| 337 | chalk.dim(" POST /exit - Gracefully shut down the server"), |
| 338 | ); |
| 339 | console.log( |
| 340 | chalk.dim( |
| 341 | `\nServer will shut down after ${timeoutSeconds} seconds of inactivity`, |
| 342 | ), |
| 343 | ); |
| 344 | |
| 345 | // If initial prompt provided, queue it for processing |
| 346 | if (actualPrompt) { |
| 347 | console.log(chalk.dim("\nProcessing initial prompt...")); |
| 348 | state.messageQueue.push(actualPrompt); |
| 349 | processMessages(state, llmApi); |
| 350 | } |
| 351 | }); |
| 352 | |
| 353 | // Process messages from the queue |
| 354 | async function processMessages(state: ServerState, llmApi: any) { |
| 355 | while (state.messageQueue.length > 0 && state.serverRunning) { |
| 356 | const userMessage = state.messageQueue.shift()!; |
| 357 | state.isProcessing = true; |
| 358 | state.shouldInterrupt = false; |
| 359 | state.lastActivity = Date.now(); |
| 360 | |
| 361 | // Add user message to history |
| 362 | state.chatHistory.push({ role: "user", content: userMessage }); |
| 363 | state.displayMessages.push({ role: "user", content: userMessage }); |
| 364 | |
| 365 | try { |
| 366 | // Create new abort controller for this response |
| 367 | state.currentAbortController = new AbortController(); |
| 368 | |
| 369 | // Stream the response with interruption support |
| 370 | await streamChatResponseWithInterruption( |
| 371 | state, |
| 372 | llmApi, |
| 373 | state.currentAbortController, |
| 374 | () => state.shouldInterrupt, |
| 375 | ); |
| 376 | |
| 377 | // Save session after successful response |
| 378 | saveSession(state.chatHistory); |
| 379 | |
| 380 | state.lastActivity = Date.now(); |
| 381 | } catch (e: any) { |
| 382 | if (e.name === "AbortError") { |
| 383 | logger.debug("Response interrupted"); |
| 384 | // Remove the partial assistant message if it exists |
| 385 | const lastMessage = state.chatHistory[state.chatHistory.length - 1]; |
| 386 | if (lastMessage.role === "assistant" && !lastMessage.content) { |
| 387 | state.chatHistory.pop(); |
| 388 | } |
| 389 | // Also remove partial display messages |
| 390 | const lastDisplayMessage = |
| 391 | state.displayMessages[state.displayMessages.length - 1]; |
| 392 | if ( |
| 393 | lastDisplayMessage && |
| 394 | lastDisplayMessage.role === "assistant" && |
| 395 | lastDisplayMessage.isStreaming |
| 396 | ) { |
| 397 | state.displayMessages.pop(); |
| 398 | } |
| 399 | } else { |
| 400 | logger.error(`Error: ${formatError(e)}`); |
| 401 | // Add error message to chat history and display messages |
| 402 | const errorMessage = `Error: ${formatError(e)}`; |
| 403 | state.chatHistory.push({ |
| 404 | role: "assistant", |
| 405 | content: errorMessage, |
| 406 | }); |
| 407 | state.displayMessages.push({ |
| 408 | role: "assistant", |
| 409 | content: errorMessage, |
| 410 | }); |
| 411 | } |
| 412 | } finally { |
| 413 | state.currentAbortController = null; |
| 414 | state.isProcessing = false; |
| 415 | } |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | // Check for inactivity and shutdown |
| 420 | inactivityChecker = setInterval(() => { |
| 421 | if (!state.isProcessing && Date.now() - state.lastActivity > timeoutMs) { |
| 422 | console.log( |
| 423 | chalk.yellow( |
| 424 | `\nShutting down due to ${timeoutSeconds} seconds of inactivity`, |
| 425 | ), |
| 426 | ); |
| 427 | state.serverRunning = false; |
| 428 | server.close(() => { |
| 429 | telemetryService.stopActiveTime(); |
| 430 | process.exit(0); |
| 431 | }); |
| 432 | if (inactivityChecker) { |
| 433 | clearInterval(inactivityChecker); |
| 434 | inactivityChecker = null; |
| 435 | } |
| 436 | } |
| 437 | }, 1000); |
| 438 | |
| 439 | // Handle graceful shutdown |
| 440 | process.on("SIGINT", () => { |
| 441 | console.log(chalk.yellow("\nShutting down server...")); |
| 442 | state.serverRunning = false; |
| 443 | if (inactivityChecker) { |
| 444 | clearInterval(inactivityChecker); |
| 445 | inactivityChecker = null; |
| 446 | } |
| 447 | server.close(() => { |
| 448 | telemetryService.stopActiveTime(); |
| 449 | process.exit(0); |
| 450 | }); |
| 451 | }); |
| 452 | } |
| 453 | |
| 454 | // Modified version of streamChatResponse that supports interruption |
| 455 | async function streamChatResponseWithInterruption( |
| 456 | state: ServerState, |
| 457 | llmApi: any, |
| 458 | abortController: AbortController, |
| 459 | shouldInterrupt: () => boolean, |
| 460 | ): Promise<string> { |
| 461 | // Import the original streamChatResponse logic but add interruption checks |
| 462 | // Create a wrapper that checks for interruption |
| 463 | const originalSignal = abortController.signal; |
| 464 | const checkInterruption = () => { |
| 465 | if (shouldInterrupt() && !originalSignal.aborted) { |
| 466 | abortController.abort(); |
| 467 | } |
| 468 | }; |
| 469 | |
| 470 | // Set up periodic interruption checks |
| 471 | const interruptionChecker = setInterval(checkInterruption, 100); |
| 472 | |
| 473 | let currentStreamingMessage: DisplayMessage | null = null; |
| 474 | |
| 475 | // Create callbacks to capture tool events |
| 476 | const callbacks: StreamCallbacks = { |
| 477 | onContent: (content: string) => { |
| 478 | if (!currentStreamingMessage) { |
| 479 | currentStreamingMessage = { |
| 480 | role: "assistant", |
| 481 | content: "", |
| 482 | isStreaming: true, |
| 483 | }; |
| 484 | state.displayMessages.push(currentStreamingMessage); |
| 485 | } |
| 486 | currentStreamingMessage.content += content; |
| 487 | }, |
| 488 | onContentComplete: (content: string) => { |
| 489 | if (currentStreamingMessage) { |
| 490 | currentStreamingMessage.content = content; |
| 491 | currentStreamingMessage.isStreaming = false; |
| 492 | currentStreamingMessage = null; |
| 493 | } else { |
| 494 | // Add complete assistant message |
| 495 | state.displayMessages.push({ |
| 496 | role: "assistant", |
| 497 | content: content, |
| 498 | isStreaming: false, |
| 499 | }); |
| 500 | } |
| 501 | }, |
| 502 | onToolStart: (toolName: string, toolArgs?: any) => { |
| 503 | // Format tool call similar to local mode |
| 504 | const formatToolCall = (name: string, args: any) => { |
| 505 | const displayName = getToolDisplayName(name); |
| 506 | if (!args) return displayName; |
| 507 | |
| 508 | const firstValue = Object.values(args)[0]; |
| 509 | const formatPath = (value: any) => { |
| 510 | if (typeof value === "string" && path.isAbsolute(value)) { |
| 511 | const workspaceRoot = process.cwd(); |
| 512 | const relativePath = path.relative(workspaceRoot, value); |
| 513 | return relativePath || value; |
| 514 | } |
| 515 | return value; |
| 516 | }; |
| 517 | |
| 518 | return `${displayName}(${formatPath(firstValue) || ""})`; |
| 519 | }; |
| 520 | |
| 521 | // If there was streaming content, finalize it first |
| 522 | if (currentStreamingMessage && currentStreamingMessage.content) { |
| 523 | currentStreamingMessage.isStreaming = false; |
| 524 | currentStreamingMessage = null; |
| 525 | } |
| 526 | |
| 527 | state.displayMessages.push({ |
| 528 | role: "system", |
| 529 | content: `○ ${formatToolCall(toolName, toolArgs)}`, |
| 530 | messageType: "tool-start", |
| 531 | toolName, |
| 532 | }); |
| 533 | }, |
| 534 | onToolResult: (result: string, toolName: string) => { |
| 535 | // Replace the tool-start message with tool-result |
| 536 | const displayName = getToolDisplayName(toolName); |
| 537 | |
| 538 | // Find and replace the corresponding tool-start message |
| 539 | for (let i = state.displayMessages.length - 1; i >= 0; i--) { |
| 540 | if ( |
| 541 | state.displayMessages[i].messageType === "tool-start" && |
| 542 | state.displayMessages[i].toolName === toolName |
| 543 | ) { |
| 544 | state.displayMessages[i] = { |
| 545 | ...state.displayMessages[i], |
| 546 | content: `● ${displayName}`, |
| 547 | messageType: "tool-result", |
| 548 | toolResult: result, |
| 549 | }; |
| 550 | return; |
| 551 | } |
| 552 | } |
| 553 | |
| 554 | // If no tool-start found, add as new message (fallback) |
| 555 | state.displayMessages.push({ |
| 556 | role: "system", |
| 557 | content: `● ${displayName}`, |
| 558 | messageType: "tool-result", |
| 559 | toolName, |
| 560 | toolResult: result, |
| 561 | }); |
| 562 | }, |
| 563 | onToolError: (error: string, toolName?: string) => { |
| 564 | state.displayMessages.push({ |
| 565 | role: "system", |
| 566 | content: `✗ Tool error: ${error}`, |
| 567 | messageType: "tool-error", |
| 568 | toolName, |
| 569 | }); |
| 570 | }, |
| 571 | onToolPermissionRequest: ( |
| 572 | toolName: string, |
| 573 | toolArgs: any, |
| 574 | requestId: string, |
| 575 | ) => { |
| 576 | // Set pending permission state |
| 577 | state.pendingPermission = { |
| 578 | toolName, |
| 579 | toolArgs, |
| 580 | requestId, |
| 581 | timestamp: Date.now(), |
| 582 | }; |
| 583 | |
| 584 | // Add a display message indicating permission is needed |
| 585 | state.displayMessages.push({ |
| 586 | role: "system", |
| 587 | content: `⚠️ Tool ${toolName} requires permission`, |
| 588 | messageType: "tool-permission-request" as any, |
| 589 | toolName, |
| 590 | }); |
| 591 | |
| 592 | // Don't wait here - the streamChatResponse will handle waiting |
| 593 | }, |
| 594 | }; |
| 595 | |
| 596 | try { |
| 597 | const response = await streamChatResponse( |
| 598 | state.chatHistory, |
| 599 | state.model, |
| 600 | llmApi, |
| 601 | abortController, |
| 602 | callbacks, |
| 603 | ); |
| 604 | return response || ""; |
| 605 | } finally { |
| 606 | clearInterval(interruptionChecker); |
| 607 | // Ensure any streaming message is finalized |
| 608 | if (currentStreamingMessage !== null) { |
| 609 | // TypeScript is having issues with this line - the message will be finalized anyway |
| 610 | // currentStreamingMessage.isStreaming = false; |
| 611 | } |
| 612 | } |
| 613 | } |