Merge pull request #104 from continuedev/json-mode

feat: json headless mode
This commit is contained in:
Nate Sesti 2025-07-29 22:16:40 -07:00 • committed by GitHub
commit 8e44284927
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 285 additions and 32 deletions

View file

@ -31,4 +31,48 @@ export default {
__filename: path.resolve(fileURLToPath(import.meta.url)),
},
resolver: "<rootDir>/jest.resolver.cjs",
// Force E2E tests to run sequentially to avoid console override conflicts
projects: [
{
displayName: "e2e",
testMatch: ["<rootDir>/src/e2e/**/*.test.ts"],
maxWorkers: 1,
transform: {
"\\.[jt]sx?$": ["ts-jest", { useESM: true }],
},
moduleNameMapper: {
"^(\\.{1,2}/.+)\\.js$": "$1",
},
extensionsToTreatAsEsm: [".ts", ".tsx"],
preset: "ts-jest/presets/default-esm",
testEnvironment: "node",
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
resolver: "<rootDir>/jest.resolver.cjs",
},
{
displayName: "unit",
testMatch: ["<rootDir>/src/**/*.test.ts"],
testPathIgnorePatterns: ["<rootDir>/src/e2e/"],
transform: {
"\\.[jt]sx?$": ["ts-jest", { useESM: true }],
},
moduleNameMapper: {
"^(\\.{1,2}/.+)\\.js$": "$1",
"^highlight\\.js/lib/languages/(.+)$":
"<rootDir>/src/ui/__mocks__/highlightLanguage.js",
"^lowlight$": "<rootDir>/src/ui/__mocks__/lowlight.js",
"^ink-testing-library$":
"<rootDir>/node_modules/ink-testing-library/build/index.js",
"^./SyntaxHighlighter\\.js$":
"<rootDir>/src/ui/__mocks__/SyntaxHighlighter.ts",
"^./FreeTrialStatus\\.js$":
"<rootDir>/src/ui/__mocks__/FreeTrialStatus.tsx",
},
extensionsToTreatAsEsm: [".ts", ".tsx"],
preset: "ts-jest/presets/default-esm",
testEnvironment: "node",
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
resolver: "<rootDir>/jest.resolver.cjs",
},
],
};

View file

@ -1,4 +1,5 @@
import { jest } from "@jest/globals";
import { resetConsoleOverrides } from "./src/util/consoleOverride.js";
// Disable telemetry for tests
process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "0";
@ -15,7 +16,7 @@ jest.mock("./src/commands/commands.js");
jest.mock("./src/services/index.js");
jest.mock("./src/services/ServiceContainerContext.js");
// Set up global afterEach hook to clear all timers
// Set up global afterEach hook to clear all timers and reset console
afterEach(() => {
// Clear jest timers only if they're available
if (typeof jest !== "undefined" && jest.clearAllTimers) {
@ -25,4 +26,11 @@ afterEach(() => {
// Ignore errors when clearing timers
}
}
// Reset console overrides to ensure clean state for each test
try {
resetConsoleOverrides();
} catch (e) {
// Ignore errors when resetting console
}
});

View file

@ -11,6 +11,7 @@ export interface CommandLineArgs {
readonly?: boolean; // Only allow readonly tools
noTools?: boolean; // Disable all tools
rules?: string[]; // Array of rule specifications
format?: 'json'; // Output format for headless mode
}
/**
@ -136,6 +137,15 @@ export function parseArgs(): CommandLineArgs {
result.noTools = true;
}
// Get format from --format flag
const formatIndex = args.indexOf("--format");
if (formatIndex !== -1 && formatIndex + 1 < args.length) {
const formatValue = args[formatIndex + 1];
if (formatValue === 'json') {
result.format = 'json';
}
}
// Get config path from --config flag
const configIndex = args.indexOf("--config");
if (configIndex !== -1 && configIndex + 1 < args.length) {
@ -160,7 +170,7 @@ export function parseArgs(): CommandLineArgs {
}
// Find the last argument that's not a flag or a flag value
const flagsWithValues = ["--config", "--rule"];
const flagsWithValues = ["--config", "--rule", "--format"];
const nonFlagArgs = args.filter((arg, index) => {
// Skip flags (starting with --)
if (arg.startsWith("--") || arg === "-p") return false;

View file

@ -12,17 +12,42 @@ import { ModelServiceState, SERVICE_NAMES } from "../services/types.js";
import { loadSession, saveSession } from "../session.js";
import { streamChatResponse } from "../streamChatResponse.js";
import { constructSystemMessage } from "../systemMessage.js";
import { posthogService } from "../telemetry/posthogService.js";
import telemetryService from "../telemetry/telemetryService.js";
import { startTUIChat } from "../ui/index.js";
import { safeStdout } from "../util/consoleOverride.js";
import { formatError } from "../util/formatError.js";
import logger from "../util/logger.js";
import { BaseCommandOptions } from "./BaseCommandOptions.js";
import { posthogService } from "../telemetry/posthogService.js";
/**
* Processes and validates JSON output for headless mode
* @param response - The raw response from the LLM
* @returns Valid JSON string
*/
function processJsonOutput(response: string): string {
const trimmedResponse = response.trim();
try {
// Try to parse the response as JSON to validate it
JSON.parse(trimmedResponse);
// If it parses successfully, return as-is
return trimmedResponse;
} catch (error) {
// If it's not valid JSON, wrap it in a JSON object
return JSON.stringify({
response: trimmedResponse,
status: "success",
note: "Response was not valid JSON, so it was wrapped in a JSON object",
});
}
}
export interface ChatOptions extends BaseCommandOptions {
headless?: boolean;
resume?: boolean;
rule?: string[]; // Array of rule specifications
format?: "json"; // Output format for headless mode
}
export async function initializeChatHistory(
@ -46,7 +71,8 @@ export async function initializeChatHistory(
const rulesSystemMessage = ""; // TODO //assistant.systemMessage;
const systemMessage = await constructSystemMessage(
rulesSystemMessage,
options.rule
options.rule,
options.format
);
if (systemMessage) {
chatHistory.push({ role: "system", content: systemMessage });
@ -61,7 +87,8 @@ async function processMessage(
chatHistory: ChatCompletionMessageParam[],
model: any,
llmApi: any,
isHeadless: boolean
isHeadless: boolean,
format?: "json"
): Promise<void> {
// Track user prompt
telemetryService.logUserPrompt(userInput.length, userInput);
@ -85,7 +112,11 @@ async function processMessage(
// In headless mode, only print the final response using safe stdout
if (isHeadless && finalResponse.trim()) {
safeStdout(finalResponse + "\n");
// Process output based on format
const outputResponse =
format === "json" ? processJsonOutput(finalResponse) : finalResponse;
safeStdout(outputResponse + "\n");
}
// Save session after each successful response
@ -140,7 +171,14 @@ async function runHeadlessMode(
isFirstMessage = false;
await processMessage(userInput, chatHistory, model, llmApi, true);
await processMessage(
userInput,
chatHistory,
model,
llmApi,
true,
options.format
);
}
}

View file

@ -0,0 +1,112 @@
import {
cleanupTestContext,
createTestContext,
runCLI,
} from "../test-helpers/cli-helpers.js";
import {
setupMockLLMTest,
cleanupMockLLMServer,
type MockLLMServer,
} from "../test-helpers/mock-llm-server.js";
describe("E2E: Headless Mode with JSON Format", () => {
let context: any;
let mockServer: MockLLMServer;
beforeEach(async () => {
context = await createTestContext();
});
afterEach(async () => {
if (mockServer) {
await cleanupMockLLMServer(mockServer);
}
await cleanupTestContext(context);
});
it("should output valid JSON when LLM returns valid JSON", async () => {
const validJsonResponse = {
response: "This is a JSON response",
status: "success",
files: ["test.ts"]
};
mockServer = await setupMockLLMTest(context, {
response: JSON.stringify(validJsonResponse),
streaming: false, // Use non-streaming to avoid JSON escaping issues
});
const result = await runCLI(context, {
args: ["-p", "--format", "json", "--config", context.configPath, "Test prompt"],
timeout: 15000,
});
// Verify the output is valid JSON
expect(() => JSON.parse(result.stdout.trim())).not.toThrow();
const parsedOutput = JSON.parse(result.stdout.trim());
expect(parsedOutput).toEqual(validJsonResponse);
expect(result.exitCode).toBe(0);
}, 20000);
it("should wrap non-JSON response in JSON object", async () => {
const nonJsonResponse = "This is just plain text response";
mockServer = await setupMockLLMTest(context, {
response: nonJsonResponse,
});
const result = await runCLI(context, {
args: ["-p", "--format", "json", "--config", context.configPath, "Test prompt"],
timeout: 15000,
});
// Verify the output is valid JSON
expect(() => JSON.parse(result.stdout.trim())).not.toThrow();
const parsedOutput = JSON.parse(result.stdout.trim());
expect(parsedOutput.response).toBe(nonJsonResponse);
expect(parsedOutput.status).toBe("success");
expect(parsedOutput.note).toBe("Response was not valid JSON, so it was wrapped in a JSON object");
expect(result.exitCode).toBe(0);
}, 20000);
it("should include JSON formatting instructions in system message", async () => {
mockServer = await setupMockLLMTest(context, {
response: '{"response": "I understand JSON format"}',
});
const result = await runCLI(context, {
args: ["-p", "--format", "json", "--config", context.configPath, "Hello"],
timeout: 15000,
});
expect(result.exitCode).toBe(0);
expect(mockServer.requests).toHaveLength(1);
// Find the system message
const systemMessage = mockServer.requests[0].body.messages.find((m: any) => m.role === "system");
expect(systemMessage.content).toContain("JSON output mode");
expect(systemMessage.content).toContain("valid JSON that can be parsed by JSON.parse()");
}, 20000);
it("should fail validation when --format is used without -p flag", async () => {
const result = await runCLI(context, {
args: ["--format", "json", "Test prompt"],
timeout: 5000,
expectError: true,
});
expect(result.stderr).toContain("--format flag can only be used with -p/--print flag");
expect(result.exitCode).toBe(1);
}, 10000);
it("should fail validation with invalid format value", async () => {
const result = await runCLI(context, {
args: ["-p", "--format", "xml", "Test prompt"],
timeout: 5000,
expectError: true,
});
expect(result.stderr).toContain("--format currently only supports 'json'");
expect(result.exitCode).toBe(1);
}, 10000);
});

View file

@ -17,25 +17,6 @@ describe("E2E: Headless Mode (Minimal)", () => {
await cleanupTestContext(context);
});
it("should show version with --version flag", async () => {
const result = await runCLI(context, {
args: ["--version"],
});
expect(result.exitCode).toBe(0);
expect(result.stdout).toMatch(/\d+\.\d+\.\d+/); // Matches version pattern
});
it("should show help with --help flag", async () => {
const result = await runCLI(context, {
args: ["--help"],
});
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("Continue CLI");
expect(result.stdout).toContain("-p, --print");
});
it("should accept a config file path", async () => {
// Create a minimal YAML config
const configPath = path.join(context.testDir, "test-config.yaml");

View file

@ -38,12 +38,30 @@ program
addCommonOptions(program)
.argument("[prompt]", "Optional prompt to send to the assistant")
.option("-p, --print", "Print response and exit (useful for pipes)")
.option(
"--format <format>",
"Output format for headless mode (json). Only works with -p/--print flag."
)
.option("--resume", "Resume from last session")
.action(async (prompt, options) => {
// Configure console overrides FIRST, before any other logging
const isHeadless = options.print;
configureConsoleForHeadless(isHeadless);
// Validate --format flag only works with -p/--print
if (options.format && !options.print) {
console.error(
"Error: --format flag can only be used with -p/--print flag"
);
process.exit(1);
}
// Validate format value
if (options.format && options.format !== "json") {
console.error("Error: --format currently only supports 'json'");
process.exit(1);
}
if (options.verbose) {
logger.setLevel("debug");
const logPath = logger.getLogPath();
@ -112,7 +130,7 @@ program
});
// Serve subcommand
const serveCommand = program
program
.command("serve [prompt]")
.description("Start an HTTP server with /state and /message endpoints")
.option(
@ -124,12 +142,12 @@ const serveCommand = program
.action(async (prompt, options) => {
// Merge parent options with subcommand options
const mergedOptions = mergeParentOptions(program, options);
if (mergedOptions.verbose) {
logger.setLevel("debug");
logger.debug("Verbose logging enabled");
}
await serve(prompt, mergedOptions);
});

View file

@ -97,11 +97,13 @@ ${getGitStatus()}
* Load and construct a comprehensive system message with base message and rules section
* @param rulesSystemMessage - The rules system message from the assistant
* @param additionalRules - Additional rules from --rule flags
* @param format - Output format for headless mode
* @returns The comprehensive system message with base message and rules section
*/
export async function constructSystemMessage(
rulesSystemMessage: string,
additionalRules?: string[]
additionalRules?: string[],
format?: "json"
): Promise<string> {
const agentFiles = ["AGENTS.md", "AGENT.md", "CLAUDE.md", "CODEX.md"];
@ -139,6 +141,18 @@ export async function constructSystemMessage(
// Construct the comprehensive system message
let systemMessage = baseSystemMessage;
// Add JSON formatting instructions if format is json
if (format === "json") {
systemMessage += `
IMPORTANT: You are operating in JSON output mode. Your final response MUST be valid JSON that can be parsed by JSON.parse(). The JSON should contain properties relevant to answer the user's question. You don't need to include any general "response" or "answer" field. Do not include any text before or after the JSON - the entire response must be parseable JSON.
Example response format:
{
"property": "value"
}`;
}
// Add rules section if we have any rules or agent content
if (rulesSystemMessage || agentContent || processedRules.length > 0) {
systemMessage += '\n\n<context name="userRules">';

View file

@ -32,6 +32,13 @@ export async function createTestContext(): Promise<CLITestContext> {
const cliPath = path.resolve("dist/index.js");
const testDir = await fs.mkdtemp(path.join(os.tmpdir(), "cn-test-"));
// Ensure the CLI file exists before returning the context
try {
await fs.access(cliPath);
} catch (error) {
throw new Error(`CLI file not found at ${cliPath}. Please run 'npm run build' first.`);
}
return {
cliPath,
testDir,

View file

@ -111,14 +111,18 @@ export async function createMockLLMServer(
const words = responseText.split(" ");
words.forEach((word, index) => {
const content = index === 0 ? word : " " + word;
// Properly escape JSON content
const escapedContent = JSON.stringify(content).slice(1, -1);
res.write(
`data: {"choices":[{"delta":{"content":"${content}"},"index":0}]}\n\n`
`data: {"choices":[{"delta":{"content":"${escapedContent}"},"index":0}]}\n\n`
);
});
} else {
// Send entire response in one chunk for non-streaming mode
// Properly escape JSON content
const escapedContent = JSON.stringify(responseText).slice(1, -1);
res.write(
`data: {"choices":[{"delta":{"content":"${responseText}"},"index":0}]}\n\n`
`data: {"choices":[{"delta":{"content":"${escapedContent}"},"index":0}]}\n\n`
);
}

View file

@ -95,4 +95,21 @@ export function withOriginalConsole<T>(fn: () => T): T {
*/
export function isInHeadlessMode(): boolean {
return isHeadlessMode;
}
/**
* Reset console overrides to original state
* Useful for testing to ensure clean state
*/
export function resetConsoleOverrides(): void {
if (originalConsole) {
console.log = originalConsole.log;
console.info = originalConsole.info;
console.warn = originalConsole.warn;
console.error = originalConsole.error;
console.debug = originalConsole.debug;
originalConsole = null;
}
isHeadlessMode = false;
}