diff --git a/src/commands/chat.ts b/src/commands/chat.ts
index 67482a8f1..72848affe 100644
--- a/src/commands/chat.ts
+++ b/src/commands/chat.ts
@@ -43,11 +43,30 @@ function processJsonOutput(response: string): string {
}
}
+/**
+ * Strips tags and excess whitespace from response
+ * @param response - The raw response from the LLM
+ * @returns Cleaned response
+ */
+function stripThinkTags(response: string): string {
+ // Remove tags and their content
+ let cleaned = response.replace(/[\s\S]*?<\/think>/g, '');
+
+ // Remove excess whitespace: multiple consecutive newlines become single newlines
+ cleaned = cleaned.replace(/\n\s*\n\s*\n/g, '\n\n');
+
+ // Trim leading and trailing whitespace
+ cleaned = cleaned.trim();
+
+ return cleaned;
+}
+
export interface ChatOptions extends ExtendedCommandOptions {
headless?: boolean;
resume?: boolean;
rule?: string[]; // Array of rule specifications
format?: "json"; // Output format for headless mode
+ silent?: boolean; // Strip tags and excess whitespace
}
export async function initializeChatHistory(
@@ -89,7 +108,8 @@ async function processMessage(
model: any,
llmApi: any,
isHeadless: boolean,
- format?: "json"
+ format?: "json",
+ silent?: boolean
): Promise {
// Track user prompt
telemetryService.logUserPrompt(userInput.length, userInput);
@@ -113,9 +133,16 @@ async function processMessage(
// In headless mode, only print the final response using safe stdout
if (isHeadless && finalResponse && finalResponse.trim()) {
+ let processedResponse = finalResponse;
+
+ // Strip think tags if --silent flag is enabled
+ if (silent) {
+ processedResponse = stripThinkTags(processedResponse);
+ }
+
// Process output based on format
const outputResponse =
- format === "json" ? processJsonOutput(finalResponse) : finalResponse;
+ format === "json" ? processJsonOutput(processedResponse) : processedResponse;
safeStdout(outputResponse + "\n");
}
@@ -187,7 +214,8 @@ async function runHeadlessMode(
model,
llmApi,
true,
- options.format
+ options.format,
+ options.silent
);
}
}
diff --git a/src/commands/stripThinkTags.test.ts b/src/commands/stripThinkTags.test.ts
new file mode 100644
index 000000000..c9e6bd638
--- /dev/null
+++ b/src/commands/stripThinkTags.test.ts
@@ -0,0 +1,160 @@
+// Unit tests for the stripThinkTags function
+
+// Since stripThinkTags is currently a private function in chat.ts,
+// we'll extract it for testing purposes. This follows the same pattern
+// as other utility functions in the codebase.
+
+/**
+ * Strips tags and excess whitespace from response
+ * @param response - The raw response from the LLM
+ * @returns Cleaned response
+ */
+function stripThinkTags(response: string): string {
+ // Remove tags and their content
+ let cleaned = response.replace(/[\s\S]*?<\/think>/g, '');
+
+ // Remove excess whitespace: multiple consecutive newlines become single newlines
+ cleaned = cleaned.replace(/\n\s*\n\s*\n/g, '\n\n');
+
+ // Trim leading and trailing whitespace
+ cleaned = cleaned.trim();
+
+ return cleaned;
+}
+
+describe("stripThinkTags", () => {
+ it("should remove simple think tags", () => {
+ const input = `
+This is a thought
+
+
+This is the actual content`;
+
+ const expected = "This is the actual content";
+ expect(stripThinkTags(input)).toBe(expected);
+ });
+
+ it("should remove multiple think tag blocks", () => {
+ const input = `First thought
+
+Content 1
+
+Second thought
+
+Content 2`;
+
+ const expected = "Content 1\n\nContent 2";
+ expect(stripThinkTags(input)).toBe(expected);
+ });
+
+ it("should handle think tags with nested content", () => {
+ const input = `
+I need to think about:
+1. Step one
+2. Step two
+ - Sub step
+
+
+Final result`;
+
+ const expected = "Final result";
+ expect(stripThinkTags(input)).toBe(expected);
+ });
+
+ it("should reduce excess whitespace", () => {
+ const input = `Remove this
+
+
+
+Content with lots of space
+
+
+
+More content`;
+
+ const expected = "Content with lots of space\n\nMore content";
+ expect(stripThinkTags(input)).toBe(expected);
+ });
+
+ it("should handle content without think tags", () => {
+ const input = `#!/bin/bash
+echo "Hello World"
+
+This has no think tags.`;
+
+ // Should return the same content (trimmed)
+ expect(stripThinkTags(input)).toBe(input.trim());
+ });
+
+ it("should handle empty think tags", () => {
+ const input = `
+
+Content after empty think tag`;
+
+ const expected = "Content after empty think tag";
+ expect(stripThinkTags(input)).toBe(expected);
+ });
+
+ it("should handle think tags at the end", () => {
+ const input = `Content at the beginning
+
+
+This thought is at the end
+`;
+
+ const expected = "Content at the beginning";
+ expect(stripThinkTags(input)).toBe(expected);
+ });
+
+ it("should handle complex whitespace patterns", () => {
+ const input = `Remove
+
+
+Content with indented whitespace
+
+
+More content`;
+
+ const result = stripThinkTags(input);
+ // Should reduce triple+ newlines to double newlines
+ expect(result).not.toMatch(/\n\s*\n\s*\n/);
+ expect(result).toContain("Content with indented whitespace");
+ expect(result).toContain("More content");
+ });
+
+ it("should handle think tags with special characters", () => {
+ const input = `
+Special chars: !@#$%^&*()
+Code: const x = () => { return "test"; }
+
+
+Actual content`;
+
+ const expected = "Actual content";
+ expect(stripThinkTags(input)).toBe(expected);
+ });
+
+ it("should be case sensitive for think tags", () => {
+ const input = `This should not be removed
+This should not be removed
+This should be removed
+
+Content`;
+
+ const result = stripThinkTags(input);
+ expect(result).toContain("This should not be removed");
+ expect(result).toContain("This should not be removed");
+ expect(result).not.toContain("This should be removed");
+ expect(result).toContain("Content");
+ });
+
+ it("should handle malformed think tags gracefully", () => {
+ const input = `Unclosed think tag
+
+Content should remain`;
+
+ // Should not remove unclosed tags
+ expect(stripThinkTags(input)).toContain("Unclosed think tag");
+ expect(stripThinkTags(input)).toContain("Content should remain");
+ });
+});
\ No newline at end of file
diff --git a/src/e2e/headless-silent-flag.test.ts b/src/e2e/headless-silent-flag.test.ts
new file mode 100644
index 000000000..d2eec2c2a
--- /dev/null
+++ b/src/e2e/headless-silent-flag.test.ts
@@ -0,0 +1,217 @@
+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 --silent Flag", () => {
+ let context: any;
+ let mockServer: MockLLMServer;
+
+ beforeEach(async () => {
+ context = await createTestContext();
+ });
+
+ afterEach(async () => {
+ if (mockServer) {
+ await cleanupMockLLMServer(mockServer);
+ }
+ await cleanupTestContext(context);
+ });
+
+ it("should strip tags from response with --silent flag", async () => {
+ const responseWithThinkTags = `
+I need to write a shell script. Let me think about this.
+The user wants a simple Hello World script.
+
+
+#!/bin/bash
+echo "Hello World"`;
+
+ mockServer = await setupMockLLMTest(context, {
+ response: responseWithThinkTags,
+ streaming: false,
+ });
+
+ const result = await runCLI(context, {
+ args: ["-p", "--silent", "--config", context.configPath, "Write a shell script"],
+ timeout: 15000,
+ });
+
+ // Verify think tags are stripped
+ expect(result.stdout).not.toContain("");
+ expect(result.stdout).not.toContain("");
+ expect(result.stdout).not.toContain("I need to write a shell script");
+
+ // Verify the actual content remains
+ expect(result.stdout).toContain("#!/bin/bash");
+ expect(result.stdout).toContain('echo "Hello World"');
+ expect(result.exitCode).toBe(0);
+ }, 20000);
+
+ it("should strip multiple blocks with --silent flag", async () => {
+ const responseWithMultipleThinkTags = `
+First thought block
+
+
+Some content here
+
+
+Second thought block
+More thinking...
+
+
+Final content`;
+
+ mockServer = await setupMockLLMTest(context, {
+ response: responseWithMultipleThinkTags,
+ streaming: false,
+ });
+
+ const result = await runCLI(context, {
+ args: ["-p", "--silent", "--config", context.configPath, "Test prompt"],
+ timeout: 15000,
+ });
+
+ // Verify all think tags are stripped
+ expect(result.stdout).not.toContain("");
+ expect(result.stdout).not.toContain("");
+ expect(result.stdout).not.toContain("First thought block");
+ expect(result.stdout).not.toContain("Second thought block");
+ expect(result.stdout).not.toContain("More thinking...");
+
+ // Verify the actual content remains
+ expect(result.stdout).toContain("Some content here");
+ expect(result.stdout).toContain("Final content");
+ expect(result.exitCode).toBe(0);
+ }, 20000);
+
+ it("should reduce excess whitespace with --silent flag", async () => {
+ const responseWithExcessWhitespace = `
+This will be removed
+
+
+
+
+Content with lots of whitespace
+
+
+
+More content`;
+
+ mockServer = await setupMockLLMTest(context, {
+ response: responseWithExcessWhitespace,
+ streaming: false,
+ });
+
+ const result = await runCLI(context, {
+ args: ["-p", "--silent", "--config", context.configPath, "Test prompt"],
+ timeout: 15000,
+ });
+
+ // Verify think tags are stripped and excess whitespace is reduced
+ expect(result.stdout).not.toContain("");
+ expect(result.stdout).not.toContain("This will be removed");
+ expect(result.stdout).toContain("Content with lots of whitespace");
+ expect(result.stdout).toContain("More content");
+
+ // Verify no triple newlines exist (excess whitespace reduced)
+ expect(result.stdout).not.toMatch(/\n\s*\n\s*\n/);
+ expect(result.exitCode).toBe(0);
+ }, 20000);
+
+ it("should work normally without --silent flag (baseline test)", async () => {
+ const responseWithThinkTags = `
+I need to write a shell script. Let me think about this.
+
+
+#!/bin/bash
+echo "Hello World"`;
+
+ mockServer = await setupMockLLMTest(context, {
+ response: responseWithThinkTags,
+ streaming: false,
+ });
+
+ const result = await runCLI(context, {
+ args: ["-p", "--config", context.configPath, "Write a shell script"],
+ timeout: 15000,
+ });
+
+ // Verify think tags are NOT stripped without --silent flag
+ expect(result.stdout).toContain("");
+ expect(result.stdout).toContain("");
+ expect(result.stdout).toContain("I need to write a shell script");
+ expect(result.stdout).toContain("#!/bin/bash");
+ expect(result.stdout).toContain('echo "Hello World"');
+ expect(result.exitCode).toBe(0);
+ }, 20000);
+
+ it("should handle response with no think tags using --silent flag", async () => {
+ const responseWithoutThinkTags = `#!/bin/bash
+echo "Hello World"
+
+This is a simple script.`;
+
+ mockServer = await setupMockLLMTest(context, {
+ response: responseWithoutThinkTags,
+ streaming: false,
+ });
+
+ const result = await runCLI(context, {
+ args: ["-p", "--silent", "--config", context.configPath, "Write a shell script"],
+ timeout: 15000,
+ });
+
+ // Verify content is preserved when no think tags exist
+ expect(result.stdout).toContain("#!/bin/bash");
+ expect(result.stdout).toContain('echo "Hello World"');
+ expect(result.stdout).toContain("This is a simple script.");
+ expect(result.exitCode).toBe(0);
+ }, 20000);
+
+ it("should fail validation when --silent is used without -p flag", async () => {
+ const result = await runCLI(context, {
+ args: ["--silent", "Test prompt"],
+ timeout: 5000,
+ expectError: true,
+ });
+
+ expect(result.stderr).toContain("--silent flag can only be used with -p/--print flag");
+ expect(result.exitCode).toBe(1);
+ }, 10000);
+
+ it("should work with both --silent and --format json flags", async () => {
+ const responseWithThinkTags = `
+I should respond with JSON
+
+
+{"message": "Hello World", "status": "success"}`;
+
+ mockServer = await setupMockLLMTest(context, {
+ response: responseWithThinkTags,
+ streaming: false,
+ });
+
+ const result = await runCLI(context, {
+ args: ["-p", "--silent", "--format", "json", "--config", context.configPath, "Test prompt"],
+ timeout: 15000,
+ });
+
+ // Verify think tags are stripped and JSON is valid
+ expect(result.stdout).not.toContain("");
+ expect(result.stdout).not.toContain("I should respond with JSON");
+
+ // Verify the output is valid JSON
+ expect(() => JSON.parse(result.stdout.trim())).not.toThrow();
+ const parsedOutput = JSON.parse(result.stdout.trim());
+ expect(parsedOutput.message).toBe("Hello World");
+ expect(parsedOutput.status).toBe("success");
+ expect(result.exitCode).toBe(0);
+ }, 20000);
+});
\ No newline at end of file
diff --git a/src/index.ts b/src/index.ts
index 5cdf34db5..b137e8761 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -42,6 +42,10 @@ addCommonOptions(program)
"--format ",
"Output format for headless mode (json). Only works with -p/--print flag."
)
+ .option(
+ "--silent",
+ "Strip tags and excess whitespace from output. Only works with -p/--print flag."
+ )
.option("--resume", "Resume from last session")
.action(async (prompt, options) => {
// Configure console overrides FIRST, before any other logging
@@ -56,6 +60,15 @@ addCommonOptions(program)
process.exit(1);
}
+ // Validate --silent flag only works with -p/--print
+ if (options.silent && !options.print) {
+ console.error(
+ "Error: --silent 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'");