feat: add --silent flag to strip thinking tags from headless output
Add --silent flag to headless mode (-p/--print) that removes <think></think> tags and excess whitespace from LLM responses. This enables clean output suitable for shell piping and automation. ## Why --silent instead of --no-think The flag was renamed from --no-think to --silent because: - Commander.js treats --no- prefix as negation flags, expecting a base --think option - --silent provides clearer semantic meaning for "quiet, clean output" - Follows Unix convention where --silent typically means suppress extra output ## Problem Solved Many models (like Nemotron - Llama 3.3 Nemotron Super 49B v1.5) emit <think></think> tags that interfere with shell piping: Without --silent: ``` $ cn -p "Echo a shell script that prints 'Hello World' Output only the script and NOTHING ELSE. No code fences. No markdown." <think> I need to write a shell script. Let me think about this. The user wants a simple Hello World script. </think> #\!/bin/bash echo "Hello World" ``` With --silent: ``` $ cn -p --silent "Echo a shell script that prints 'Hello World' Output only the script and NOTHING ELSE. No code fences. No markdown." #\!/bin/bash echo "Hello World" ``` This makes piping work correctly: ``` $ eval $(cn -p --silent "Write a shell script that prints 'Hello World'") Hello World ``` ## Features - Strips all <think></think> blocks and their content - Reduces excessive whitespace (3+ consecutive newlines become 2) - Works with --format json flag - Includes comprehensive unit and e2e tests - Only available with -p/--print flag (headless mode)
This commit is contained in:
parent
a0a053a740
commit
8fa31ed082
4 changed files with 421 additions and 3 deletions
|
|
@ -43,11 +43,30 @@ function processJsonOutput(response: string): string {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips <think></think> tags and excess whitespace from response
|
||||
* @param response - The raw response from the LLM
|
||||
* @returns Cleaned response
|
||||
*/
|
||||
function stripThinkTags(response: string): string {
|
||||
// Remove <think></think> tags and their content
|
||||
let cleaned = response.replace(/<think>[\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 <think></think> 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<void> {
|
||||
// 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
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
160
src/commands/stripThinkTags.test.ts
Normal file
160
src/commands/stripThinkTags.test.ts
Normal file
|
|
@ -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 <think></think> tags and excess whitespace from response
|
||||
* @param response - The raw response from the LLM
|
||||
* @returns Cleaned response
|
||||
*/
|
||||
function stripThinkTags(response: string): string {
|
||||
// Remove <think></think> tags and their content
|
||||
let cleaned = response.replace(/<think>[\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 = `<think>
|
||||
This is a thought
|
||||
</think>
|
||||
|
||||
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 = `<think>First thought</think>
|
||||
|
||||
Content 1
|
||||
|
||||
<think>Second thought</think>
|
||||
|
||||
Content 2`;
|
||||
|
||||
const expected = "Content 1\n\nContent 2";
|
||||
expect(stripThinkTags(input)).toBe(expected);
|
||||
});
|
||||
|
||||
it("should handle think tags with nested content", () => {
|
||||
const input = `<think>
|
||||
I need to think about:
|
||||
1. Step one
|
||||
2. Step two
|
||||
- Sub step
|
||||
</think>
|
||||
|
||||
Final result`;
|
||||
|
||||
const expected = "Final result";
|
||||
expect(stripThinkTags(input)).toBe(expected);
|
||||
});
|
||||
|
||||
it("should reduce excess whitespace", () => {
|
||||
const input = `<think>Remove this</think>
|
||||
|
||||
|
||||
|
||||
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 = `<think></think>
|
||||
|
||||
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
|
||||
|
||||
<think>
|
||||
This thought is at the end
|
||||
</think>`;
|
||||
|
||||
const expected = "Content at the beginning";
|
||||
expect(stripThinkTags(input)).toBe(expected);
|
||||
});
|
||||
|
||||
it("should handle complex whitespace patterns", () => {
|
||||
const input = `<think>Remove</think>
|
||||
|
||||
|
||||
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 = `<think>
|
||||
Special chars: !@#$%^&*()
|
||||
Code: const x = () => { return "test"; }
|
||||
</think>
|
||||
|
||||
Actual content`;
|
||||
|
||||
const expected = "Actual content";
|
||||
expect(stripThinkTags(input)).toBe(expected);
|
||||
});
|
||||
|
||||
it("should be case sensitive for think tags", () => {
|
||||
const input = `<THINK>This should not be removed</THINK>
|
||||
<Think>This should not be removed</Think>
|
||||
<think>This should be removed</think>
|
||||
|
||||
Content`;
|
||||
|
||||
const result = stripThinkTags(input);
|
||||
expect(result).toContain("<THINK>This should not be removed</THINK>");
|
||||
expect(result).toContain("<Think>This should not be removed</Think>");
|
||||
expect(result).not.toContain("<think>This should be removed</think>");
|
||||
expect(result).toContain("Content");
|
||||
});
|
||||
|
||||
it("should handle malformed think tags gracefully", () => {
|
||||
const input = `<think>Unclosed think tag
|
||||
|
||||
Content should remain`;
|
||||
|
||||
// Should not remove unclosed tags
|
||||
expect(stripThinkTags(input)).toContain("<think>Unclosed think tag");
|
||||
expect(stripThinkTags(input)).toContain("Content should remain");
|
||||
});
|
||||
});
|
||||
217
src/e2e/headless-silent-flag.test.ts
Normal file
217
src/e2e/headless-silent-flag.test.ts
Normal file
|
|
@ -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 <think></think> tags from response with --silent flag", async () => {
|
||||
const responseWithThinkTags = `<think>
|
||||
I need to write a shell script. Let me think about this.
|
||||
The user wants a simple Hello World script.
|
||||
</think>
|
||||
|
||||
#!/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("<think>");
|
||||
expect(result.stdout).not.toContain("</think>");
|
||||
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 <think></think> blocks with --silent flag", async () => {
|
||||
const responseWithMultipleThinkTags = `<think>
|
||||
First thought block
|
||||
</think>
|
||||
|
||||
Some content here
|
||||
|
||||
<think>
|
||||
Second thought block
|
||||
More thinking...
|
||||
</think>
|
||||
|
||||
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("<think>");
|
||||
expect(result.stdout).not.toContain("</think>");
|
||||
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 = `<think>
|
||||
This will be removed
|
||||
</think>
|
||||
|
||||
|
||||
|
||||
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("<think>");
|
||||
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 = `<think>
|
||||
I need to write a shell script. Let me think about this.
|
||||
</think>
|
||||
|
||||
#!/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("<think>");
|
||||
expect(result.stdout).toContain("</think>");
|
||||
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 = `<think>
|
||||
I should respond with JSON
|
||||
</think>
|
||||
|
||||
{"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("<think>");
|
||||
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);
|
||||
});
|
||||
13
src/index.ts
13
src/index.ts
|
|
@ -42,6 +42,10 @@ addCommonOptions(program)
|
|||
"--format <format>",
|
||||
"Output format for headless mode (json). Only works with -p/--print flag."
|
||||
)
|
||||
.option(
|
||||
"--silent",
|
||||
"Strip <think></think> 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'");
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue