Skip to main content

Overview

Headless mode allows you to run Qwen Code without the interactive UI, making it ideal for:
  • CI/CD pipelines
  • Automation scripts
  • Batch processing
  • Integration with other tools
  • Programmatic access
Headless mode executes a single prompt and exits, optionally outputting structured data.

Basic Usage

# Execute a prompt and exit
qwen --prompt "Fix all TypeScript errors in src/"

# Short form
qwen -p "Add unit tests for the auth module"

Output Formats

Human-readable text output:
qwen --prompt "List all TODO comments" --output text
Output:
I found 3 TODO comments in your codebase:

1. src/auth.ts:42 - TODO: Add rate limiting
2. src/db.ts:156 - TODO: Implement connection pooling
3. tests/e2e.ts:23 - TODO: Add timeout handling

Input Formats

Standard Input

# Pipe content to qwen
cat requirements.txt | qwen --prompt "Create a project from these requirements"

# Use heredoc
qwen --prompt "Review this code" <<EOF
function add(a, b) {
  return a + b;
}
EOF

File Input

Use @include to reference files:
qwen --prompt "Fix bugs in @include(src/auth.ts)"

Stream JSON Input

For advanced integrations:
# Send structured input
qwen --input stream-json --output stream-json <<EOF
{"type":"user_message","content":"Analyze the codebase"}
EOF

Approval Modes in Headless

In headless mode with default approval, tools requiring approval will fail. Use yolo or auto-edit mode for automation.
Auto-approve all actions:
qwen --prompt "Deploy to production" --approval-mode yolo
YOLO mode executes all actions without confirmation. Use with caution!

Environment Variables

# Set API key
export GOOGLE_API_KEY="your-key-here"

# Configure model
export QWEN_MODEL="gemini-2.5-pro"

# Set working directory
export QWEN_WORKDIR="/path/to/project"

# Disable telemetry
export QWEN_TELEMETRY=false

# Set approval mode
export QWEN_APPROVAL_MODE=yolo

Exit Codes

CodeMeaning
0Success
1General error
2Authentication error
3Tool execution failed
4Context limit exceeded
5Invalid configuration
# Check exit code
qwen --prompt "Run tests"
if [ $? -eq 0 ]; then
  echo "Success"
else
  echo "Failed with code $?"
fi

Advanced Examples

CI/CD Integration

# .github/workflows/ai-review.yml
name: AI Code Review
on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Install Qwen Code
        run: npm install -g @qwen-code/cli
      - name: Run AI Review
        env:
          GOOGLE_API_KEY: ${{ secrets.GOOGLE_API_KEY }}
        run: |
          qwen --prompt "Review changes in this PR" \
               --approval-mode plan \
               --output json > review.json
      - name: Post Comment
        run: gh pr comment --body-file review.json

Batch Processing

#!/bin/bash
# Process multiple files
for file in src/**/*.ts; do
  echo "Processing $file..."
  qwen --prompt "Add JSDoc comments to @include($file)" \
       --approval-mode auto-edit \
       --output text
done

Automation Script

#!/bin/bash
# Daily maintenance script

set -e

# Update dependencies
qwen -p "Update package.json dependencies to latest versions" --approval-mode yolo

# Run tests
qwen -p "Run the test suite and fix any failures" --approval-mode yolo

# Generate report
qwen -p "Create a summary of changes" --output json > daily-report.json

echo "Maintenance complete!"

Timeouts and Limits

# Set maximum session turns (default: 100)
qwen --prompt "Complex task" --max-turns 50

# Set operation timeout (in seconds)
timeout 300 qwen --prompt "Long-running analysis"

Debugging Headless Runs

# Enable debug output
DEBUG=qwen:* qwen --prompt "Debug this issue" 2> debug.log

# Verbose output
qwen --prompt "Analyze" --output json --verbose

# Save full session
qwen --prompt "Task" --output stream-json > session.jsonl

Error Handling

#!/bin/bash

if ! output=$(qwen --prompt "Fix bugs" --approval-mode yolo 2>&1); then
  echo "Qwen failed: $output" >&2
  # Send alert
  curl -X POST https://alerts.example.com \
    -d "{\"error\": \"$output\"}"
  exit 1
fi

echo "Success: $output"

Limitations

Tools that require user input (like ask_user_question) will fail in headless mode.Workaround: Use YOLO mode to skip confirmations, or provide input upfront.
Each invocation processes one prompt. For multi-turn conversations, use interactive mode.Workaround: Chain multiple invocations or use the ACP protocol for stateful sessions.
Progress indicators and rich formatting aren’t available.Workaround: Use stream-json output to implement your own progress tracking.
Headless sessions aren’t saved to disk unless explicitly configured.Workaround: Use --save-session flag or export output to a file.

Best Practices

  1. Always use --approval-mode yolo or auto-edit in automation
  2. Set reasonable --max-turns to prevent infinite loops
  3. Use --output stream-json for real-time processing
  4. Implement proper error handling with exit codes
  5. Set timeouts to prevent hanging processes
  6. Log debug output for troubleshooting
  7. Use environment variables for configuration
  8. Test scripts locally before deploying to CI/CD

Next Steps

Approval Modes

Understand permission modes for automation

Session Commands

Learn available commands (some work in headless)

MCP Integration

Extend with Model Context Protocol servers

Interactive Mode

Switch to interactive UI for complex tasks