> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/QwenLM/qwen-code/llms.txt
> Use this file to discover all available pages before exploring further.

# Headless Mode

> Running Qwen Code non-interactively for scripts and automation

## 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

```bash theme={null}
# 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

<Tabs>
  <Tab title="Text (Default)">
    Human-readable text output:

    ```bash theme={null}
    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
    ```
  </Tab>

  <Tab title="JSON">
    Structured JSON output:

    ```bash theme={null}
    qwen --prompt "Analyze this file" --output json
    ```

    Output:

    ```json theme={null}
    {
      "messages": [
        {
          "role": "system",
          "timestamp": "2026-03-10T20:00:00Z",
          "content": "Session initialized"
        },
        {
          "role": "user",
          "timestamp": "2026-03-10T20:00:01Z",
          "content": "Analyze this file"
        },
        {
          "role": "assistant",
          "timestamp": "2026-03-10T20:00:05Z",
          "content": "This file implements..."
        }
      ],
      "result": {
        "isError": false,
        "durationMs": 4523,
        "numTurns": 1,
        "usage": {
          "inputTokens": 1234,
          "outputTokens": 567
        }
      }
    }
    ```
  </Tab>

  <Tab title="Stream JSON">
    Streaming JSON for real-time processing:

    ```bash theme={null}
    qwen --prompt "Refactor this code" --output stream-json
    ```

    Each line is a JSON event:

    ```json theme={null}
    {"type":"system_message","timestamp":"...","content":"Session initialized"}
    {"type":"user_message","timestamp":"...","content":"Refactor this code"}
    {"type":"assistant_message_start","timestamp":"..."}
    {"type":"content","value":"I'll refactor this code..."}
    {"type":"tool_call","name":"edit","args":{"filePath":"..."}}
    {"type":"tool_result","success":true}
    {"type":"assistant_message_end"}
    {"type":"result","isError":false,"durationMs":3421}
    ```
  </Tab>
</Tabs>

## Input Formats

### Standard Input

```bash theme={null}
# 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:

```bash theme={null}
qwen --prompt "Fix bugs in @include(src/auth.ts)"
```

### Stream JSON Input

For advanced integrations:

```bash theme={null}
# Send structured input
qwen --input stream-json --output stream-json <<EOF
{"type":"user_message","content":"Analyze the codebase"}
EOF
```

## Approval Modes in Headless

<Warning>
  In headless mode with `default` approval, tools requiring approval will fail. Use `yolo` or `auto-edit` mode for automation.
</Warning>

<Tabs>
  <Tab title="YOLO Mode">
    Auto-approve all actions:

    ```bash theme={null}
    qwen --prompt "Deploy to production" --approval-mode yolo
    ```

    <Warning>
      YOLO mode executes all actions without confirmation. Use with caution!
    </Warning>
  </Tab>

  <Tab title="Auto Edit Mode">
    Auto-approve file edits only:

    ```bash theme={null}
    qwen --prompt "Refactor codebase" --approval-mode auto-edit
    ```

    Shell commands still require approval (will fail in headless).
  </Tab>

  <Tab title="Plan Mode">
    Analysis only, no modifications:

    ```bash theme={null}
    qwen --prompt "What needs fixing?" --approval-mode plan
    ```

    AI analyzes but doesn't execute tools that modify files or run commands.
  </Tab>
</Tabs>

## Environment Variables

```bash theme={null}
# 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

| Code | Meaning                |
| ---- | ---------------------- |
| `0`  | Success                |
| `1`  | General error          |
| `2`  | Authentication error   |
| `3`  | Tool execution failed  |
| `4`  | Context limit exceeded |
| `5`  | Invalid configuration  |

```bash theme={null}
# Check exit code
qwen --prompt "Run tests"
if [ $? -eq 0 ]; then
  echo "Success"
else
  echo "Failed with code $?"
fi
```

## Advanced Examples

### CI/CD Integration

```yaml theme={null}
# .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

```bash theme={null}
#!/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

```bash theme={null}
#!/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

```bash theme={null}
# 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

```bash theme={null}
# 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

<Tabs>
  <Tab title="Shell Script">
    ```bash theme={null}
    #!/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"
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import subprocess
    import json

    try:
        result = subprocess.run(
            ['qwen', '--prompt', 'Analyze code', '--output', 'json'],
            capture_output=True,
            text=True,
            check=True,
            timeout=300
        )
        data = json.loads(result.stdout)
        print(f"Success: {data['result']}")
    except subprocess.CalledProcessError as e:
        print(f"Qwen failed with code {e.returncode}")
        print(f"Error: {e.stderr}")
    except subprocess.TimeoutExpired:
        print("Qwen timed out after 5 minutes")
    ```
  </Tab>

  <Tab title="Node.js">
    ```javascript theme={null}
    const { spawn } = require('child_process');

    const qwen = spawn('qwen', [
      '--prompt', 'Generate tests',
      '--output', 'stream-json',
      '--approval-mode', 'yolo'
    ]);

    let output = '';

    qwen.stdout.on('data', (data) => {
      output += data.toString();
      // Process streaming JSON
      const lines = output.split('\n');
      for (const line of lines.slice(0, -1)) {
        try {
          const event = JSON.parse(line);
          console.log('Event:', event.type);
        } catch (e) {
          // Incomplete line
        }
      }
      output = lines[lines.length - 1];
    });

    qwen.on('close', (code) => {
      if (code === 0) {
        console.log('Success');
      } else {
        console.error(`Failed with code ${code}`);
      }
    });
    ```
  </Tab>
</Tabs>

## Limitations

<AccordionGroup>
  <Accordion title="No user input prompts">
    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.
  </Accordion>

  <Accordion title="Limited to single prompt">
    Each invocation processes one prompt. For multi-turn conversations, use interactive mode.

    **Workaround:** Chain multiple invocations or use the ACP protocol for stateful sessions.
  </Accordion>

  <Accordion title="No visual feedback">
    Progress indicators and rich formatting aren't available.

    **Workaround:** Use `stream-json` output to implement your own progress tracking.
  </Accordion>

  <Accordion title="Session not persisted by default">
    Headless sessions aren't saved to disk unless explicitly configured.

    **Workaround:** Use `--save-session` flag or export output to a file.
  </Accordion>
</AccordionGroup>

## 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

<CardGroup cols={2}>
  <Card title="Approval Modes" icon="shield" href="/features/approval-modes">
    Understand permission modes for automation
  </Card>

  <Card title="Session Commands" icon="terminal" href="/features/commands">
    Learn available commands (some work in headless)
  </Card>

  <Card title="MCP Integration" icon="plug" href="/features/mcp">
    Extend with Model Context Protocol servers
  </Card>

  <Card title="Interactive Mode" icon="window" href="/features/interactive-mode">
    Switch to interactive UI for complex tasks
  </Card>
</CardGroup>
