diff --git a/package-lock.json b/package-lock.json index 79f4ac739..8bf2785b0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -21,6 +21,7 @@ "@opentelemetry/resources": "^2.0.1", "@opentelemetry/sdk-node": "^0.203.0", "@opentelemetry/semantic-conventions": "^1.36.0", + "@types/express": "^5.0.3", "@types/react": "^19.1.8", "@types/turndown": "^5.0.5", "@workos-inc/node": "^7.45.0", @@ -28,6 +29,7 @@ "commander": "^14.0.0", "diff": "^7.0.0", "dotenv": "^16.5.0", + "express": "^5.1.0", "glob": "^11.0.3", "ignore-walk": "^7.0.0", "ink": "^6.0.1", @@ -4727,22 +4729,19 @@ "license": "MIT" }, "node_modules/@types/express": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.21.tgz", - "integrity": "sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ==", - "license": "MIT", + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.3.tgz", + "integrity": "sha512-wGA0NX93b19/dZC1J18tKWVIYWyyF2ZjT9vin/NRu0qzzvfVzWjs04iq2rQ3H65vCTQYlRqs3YHfY7zjdV+9Kw==", "dependencies": { "@types/body-parser": "*", - "@types/express-serve-static-core": "^4.17.33", - "@types/qs": "*", + "@types/express-serve-static-core": "^5.0.0", "@types/serve-static": "*" } }, "node_modules/@types/express-serve-static-core": { - "version": "4.19.6", - "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.6.tgz", - "integrity": "sha512-N4LZ2xG7DatVqhCZzOGb1Yi5lMbXSZcmdLDe9EzSndPV2HpWYWzRbaerl2n27irrm94EPpprqa8KpskPT085+A==", - "license": "MIT", + "version": "5.0.7", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.0.7.tgz", + "integrity": "sha512-R+33OsgWw7rOhD1emjU7dzCDHucJrgJXMA5PYCzJxVil0dsyx5iBEPHqpPfiKNJQb7lZ1vxwoLR4Z87bBUpeGQ==", "dependencies": { "@types/node": "*", "@types/qs": "*", @@ -4954,16 +4953,14 @@ "dev": true }, "node_modules/@types/qs": { - "version": "6.9.18", - "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.18.tgz", - "integrity": "sha512-kK7dgTYDyGqS+e2Q4aK9X3D7q234CIZ1Bv0q/7Z5IwRDoADNU81xXJK/YVyLbLTZCoIwUoDoffFeF+p/eIklAA==", - "license": "MIT" + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ==" }, "node_modules/@types/range-parser": { "version": "1.2.7", "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", - "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", - "license": "MIT" + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==" }, "node_modules/@types/react": { "version": "19.1.8", @@ -7264,7 +7261,6 @@ "version": "5.1.0", "resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz", "integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==", - "license": "MIT", "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.0", @@ -8626,6 +8622,28 @@ } } }, + "node_modules/iron-session/node_modules/@types/express": { + "version": "4.17.23", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.23.tgz", + "integrity": "sha512-Crp6WY9aTYP3qPi2wGDo9iUe/rceX01UMhnF1jmwDcKCFM6cx7YhGP/Mpr3y9AASpfHixIG0E6azCcL5OcDHsQ==", + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "*" + } + }, + "node_modules/iron-session/node_modules/@types/express-serve-static-core": { + "version": "4.19.6", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.6.tgz", + "integrity": "sha512-N4LZ2xG7DatVqhCZzOGb1Yi5lMbXSZcmdLDe9EzSndPV2HpWYWzRbaerl2n27irrm94EPpprqa8KpskPT085+A==", + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, "node_modules/iron-session/node_modules/@types/node": { "version": "17.0.45", "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.45.tgz", diff --git a/package.json b/package.json index e808847e5..63d824587 100644 --- a/package.json +++ b/package.json @@ -43,6 +43,7 @@ "@opentelemetry/resources": "^2.0.1", "@opentelemetry/sdk-node": "^0.203.0", "@opentelemetry/semantic-conventions": "^1.36.0", + "@types/express": "^5.0.3", "@types/react": "^19.1.8", "@types/turndown": "^5.0.5", "@workos-inc/node": "^7.45.0", @@ -50,6 +51,7 @@ "commander": "^14.0.0", "diff": "^7.0.0", "dotenv": "^16.5.0", + "express": "^5.1.0", "glob": "^11.0.3", "ignore-walk": "^7.0.0", "ink": "^6.0.1", diff --git a/src/commands/serve.ts b/src/commands/serve.ts new file mode 100644 index 000000000..65a127f8f --- /dev/null +++ b/src/commands/serve.ts @@ -0,0 +1,264 @@ +import chalk from "chalk"; +import express, { Request, Response } from "express"; +import type { ChatCompletionMessageParam } from "openai/resources.mjs"; +import { + ensureOrganization, + getOrganizationId, + loadAuthConfig, +} from "../auth/workos.js"; +import { initializeWithOnboarding } from "../onboarding.js"; +import { saveSession } from "../session.js"; +import { constructSystemMessage } from "../systemMessage.js"; +import telemetryService from "../telemetry/telemetryService.js"; +import { formatError } from "../util/formatError.js"; +import logger from "../util/logger.js"; + +interface ServeOptions { + config?: string; + readonly?: boolean; + noTools?: boolean; + verbose?: boolean; + rule?: string[]; + timeout?: string; + port?: string; +} + +interface ServerState { + chatHistory: ChatCompletionMessageParam[]; + config: any; + model: any; + isProcessing: boolean; + lastActivity: number; + messageQueue: string[]; + currentAbortController: AbortController | null; + shouldInterrupt: boolean; + serverRunning: boolean; +} + +export async function serve(prompt?: string, options: ServeOptions = {}) { + const timeoutSeconds = parseInt(options.timeout || "300", 10); + const timeoutMs = timeoutSeconds * 1000; + const port = parseInt(options.port || "8000", 10); + + // Initialize authentication + const authConfig = loadAuthConfig(); + + // Initialize with onboarding + const { config, llmApi, model } = await initializeWithOnboarding( + authConfig, + options.config, + options.rule + ); + + // Ensure organization is selected if authenticated + let finalAuthConfig = authConfig; + if (config && authConfig) { + finalAuthConfig = await ensureOrganization(authConfig, true); // headless mode + if (finalAuthConfig) { + const organizationId = getOrganizationId(finalAuthConfig); + if (organizationId) { + telemetryService.updateOrganization(organizationId); + } + } + } + + // Initialize chat history + let chatHistory: ChatCompletionMessageParam[] = []; + const systemMessage = await constructSystemMessage("", options.rule); + if (systemMessage) { + chatHistory.push({ role: "system", content: systemMessage }); + } + + // Initialize server state + const state: ServerState = { + chatHistory, + config, + model, + isProcessing: false, + lastActivity: Date.now(), + messageQueue: [], + currentAbortController: null, + shouldInterrupt: false, + serverRunning: true, + }; + + // Record session start + telemetryService.recordSessionStart(); + telemetryService.startActiveTime(); + + const app = express(); + app.use(express.json()); + + // GET /state - Return the current state + app.get("/state", (_req: Request, res: Response) => { + state.lastActivity = Date.now(); + res.json({ + chatHistory: state.chatHistory, + isProcessing: state.isProcessing, + messageQueueLength: state.messageQueue.length, + }); + }); + + // POST /message - Queue a message and potentially interrupt + app.post("/message", async (req: Request, res: Response) => { + state.lastActivity = Date.now(); + + const { message } = req.body; + if (!message) { + return res.status(400).json({ error: "Message field is required" }); + } + + // Queue the message + state.messageQueue.push(message); + + // If currently processing, set interrupt flag + if (state.isProcessing && state.currentAbortController) { + state.shouldInterrupt = true; + } + + res.json({ + queued: true, + position: state.messageQueue.length, + willInterrupt: state.shouldInterrupt, + }); + + // Process messages if not already processing + if (!state.isProcessing) { + processMessages(state, llmApi); + } + }); + + const server = app.listen(port, () => { + console.log(chalk.green(`Server started on http://localhost:${port}`)); + console.log(chalk.dim("Endpoints:")); + console.log(chalk.dim(" GET /state - Get current agent state")); + console.log( + chalk.dim(" POST /message - Send a message (body: { message: string })") + ); + console.log( + chalk.dim( + `\nServer will shut down after ${timeoutSeconds} seconds of inactivity` + ) + ); + + // If initial prompt provided, queue it for processing + if (prompt) { + console.log(chalk.dim("\nProcessing initial prompt...")); + state.messageQueue.push(prompt); + processMessages(state, llmApi); + } + }); + + // Process messages from the queue + async function processMessages(state: ServerState, llmApi: any) { + while (state.messageQueue.length > 0 && state.serverRunning) { + const userMessage = state.messageQueue.shift()!; + state.isProcessing = true; + state.shouldInterrupt = false; + state.lastActivity = Date.now(); + + // Add user message to history + state.chatHistory.push({ role: "user", content: userMessage }); + + try { + // Create new abort controller for this response + state.currentAbortController = new AbortController(); + + // Stream the response with interruption support + await streamChatResponseWithInterruption( + state.chatHistory, + state.model, + llmApi, + state.currentAbortController, + () => state.shouldInterrupt + ); + + // Save session after successful response + saveSession(state.chatHistory); + + state.lastActivity = Date.now(); + } catch (e: any) { + if (e.name === "AbortError") { + logger.debug("Response interrupted"); + // Remove the partial assistant message if it exists + const lastMessage = state.chatHistory[state.chatHistory.length - 1]; + if (lastMessage.role === "assistant" && !lastMessage.content) { + state.chatHistory.pop(); + } + } else { + logger.error(`Error: ${formatError(e)}`); + // Add error message to chat history + state.chatHistory.push({ + role: "assistant", + content: `Error: ${formatError(e)}`, + }); + } + } finally { + state.currentAbortController = null; + state.isProcessing = false; + } + } + } + + // Check for inactivity and shutdown + const inactivityChecker = setInterval(() => { + if (!state.isProcessing && Date.now() - state.lastActivity > timeoutMs) { + console.log( + chalk.yellow( + `\nShutting down due to ${timeoutSeconds} seconds of inactivity` + ) + ); + state.serverRunning = false; + server.close(() => { + telemetryService.stopActiveTime(); + process.exit(0); + }); + clearInterval(inactivityChecker); + } + }, 1000); + + // Handle graceful shutdown + process.on("SIGINT", () => { + console.log(chalk.yellow("\nShutting down server...")); + state.serverRunning = false; + server.close(() => { + telemetryService.stopActiveTime(); + process.exit(0); + }); + }); +} + +// Modified version of streamChatResponse that supports interruption +async function streamChatResponseWithInterruption( + chatHistory: ChatCompletionMessageParam[], + model: any, + llmApi: any, + abortController: AbortController, + shouldInterrupt: () => boolean +): Promise { + // Import the original streamChatResponse logic but add interruption checks + const { streamChatResponse } = await import("../streamChatResponse.js"); + + // Create a wrapper that checks for interruption + const originalSignal = abortController.signal; + const checkInterruption = () => { + if (shouldInterrupt() && !originalSignal.aborted) { + abortController.abort(); + } + }; + + // Set up periodic interruption checks + const interruptionChecker = setInterval(checkInterruption, 100); + + try { + const response = await streamChatResponse( + chatHistory, + model, + llmApi, + abortController + ); + return response; + } finally { + clearInterval(interruptionChecker); + } +} diff --git a/src/index.ts b/src/index.ts index 154362b92..3d45f2e08 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,6 +5,7 @@ import { chat } from "./commands/chat.js"; import { login } from "./commands/login.js"; import { logout } from "./commands/logout.js"; import { remote } from "./commands/remote.js"; +import { serve } from "./commands/serve.js"; import { configureConsoleForHeadless } from "./util/consoleOverride.js"; import logger from "./util/logger.js"; import { getVersion } from "./version.js"; @@ -96,6 +97,38 @@ program await remote(prompt); }); +// Serve subcommand +program + .command("serve [prompt]") + .description("Start an HTTP server with /state and /message endpoints") + .option("--config ", "Path to configuration file") + .option("--readonly", "Only allow readonly tools") + .option("--no-tools", "Disable all tools") + .option("-v, --verbose", "Enable verbose logging") + .option( + "--rule ", + "Add a rule (can be a file path, hub slug, or string content). Can be specified multiple times.", + (value: string, previous: string[] | undefined) => { + const array = Array.isArray(previous) ? previous : []; + array.push(value); + return array; + }, + [] as string[] + ) + .option( + "--timeout ", + "Inactivity timeout in seconds (default: 300)", + "300" + ) + .option("--port ", "Port to run the server on (default: 8000)", "8000") + .action(async (prompt, options) => { + if (options.verbose) { + logger.setLevel("debug"); + logger.debug("Verbose logging enabled"); + } + await serve(prompt, options); + }); + // Handle unknown commands program.on("command:*", () => { console.error(`Error: Unknown command '${program.args.join(" ")}'\n`); diff --git a/test-serve.sh b/test-serve.sh new file mode 100755 index 000000000..9a1c90b5d --- /dev/null +++ b/test-serve.sh @@ -0,0 +1,35 @@ +#!/bin/bash + +echo "Testing the cn serve command" +echo "============================" +echo "" +echo "1. Starting server with initial prompt in the background..." +npm run dev -- serve "What is the capital of France?" --timeout 10 & +SERVER_PID=$! + +# Wait for server to start +sleep 3 + +echo "" +echo "2. Checking server state..." +curl -s http://localhost:8000/state | jq . + +echo "" +echo "3. Sending a message..." +curl -s -X POST http://localhost:8000/message \ + -H "Content-Type: application/json" \ + -d '{"message": "What is 2+2?"}' | jq . + +# Wait for response to process +sleep 3 + +echo "" +echo "4. Checking state after message..." +curl -s http://localhost:8000/state | jq . + +echo "" +echo "5. Server will shut down after 10 seconds of inactivity..." +echo "(You can send more messages with: curl -X POST http://localhost:8000/message -H 'Content-Type: application/json' -d '{\"message\": \"Your message here\"}')" + +# Wait for the server process to complete +wait $SERVER_PID \ No newline at end of file