AI & Agents

How to Run Cline in Headless Mode for CI/CD and Script Automation

Running Cline in headless mode enables developers to execute coding tasks in non-interactive CI/CD environments and automated shell scripts. By combining headless activation triggers, automated tool approvals, and structured JSON streams, engineering teams can automate code reviews, test repairs, and documentation updates unattended. Connecting background pipelines to shared cloud workspaces ensures that generated artifacts and execution records remain persistent and auditable.

Fast.io Editorial Team 14 min read
Running Cline CLI in headless mode for automated CI/CD pipelines and unattended scripting.

How Headless Mode Operates in the Cline CLI

Running an interactive coding assistant inside an open code editor works well for guided refactoring, but unattended terminal pipelines fail the instant a process prompts for interactive confirmation or attempts to render an interactive terminal user interface. Autonomous continuous integration runners and scheduled shell scripts have no human sitting at a keyboard to press confirmation keys or inspect diff dialogues. When an agent runs unattended, it must start without a graphical desktop, accept inputs from upstream pipes, execute changes autonomously, and stream machine-readable logs to downstream steps.

Cline headless mode enables developers to run the Cline coding agent in non-interactive terminal pipelines, automatically executing tasks with JSON output and automated approvals for CI/CD workflows. The Cline command line interface provides native support for this operational model. Rather than forcing you to maintain a virtual framebuffer or launch an electron shell in a headless container, the Cline CLI detects non-interactive invocation patterns and switches its execution mode automatically.

Headless mode activates in the Cline CLI under three distinct conditions:

  1. Standard input is piped: When an upstream command streams text into the CLI, Cline reads the input stream as task context and suppresses interactive prompts.
  2. Standard output is redirected: When terminal output is routed to a flat file, a downstream tool, or a Unix pipe, the CLI disables interactive terminal controls.
  3. Structured output is requested: Passing the --json flag explicitly instructs the agent to emit newline-delimited JSON objects instead of formatted terminal text.
Invocation Pattern Activation Trigger Execution Behavior
cline --json "task" JSON flag supplied Emits newline-delimited JSON events without rendering terminal styles
git diff | cline "task" stdin is piped Consumes piped stream into context and bypasses prompt dialogues
cline "task" > output.txt stdout redirected Suppresses interactive cursor movements and writes plain text stream

For quick script automation, a practical bash one-liner pipes context directly into a headless Cline instance:

git diff | cline --auto-approve true --json "review these changes for regressions" | jq -r '.text'

Interactive sessions run through the terminal user interface launched by cline or cline -i. In contrast, headless execution operates as an ephemeral batch task. The process starts, performs its requested file edits or analysis, writes structured events to stdout, and exits with a standard process status code once the objective is complete.

How to Configure Non-Interactive Flags and Execution Guardrails

Running an autonomous agent in a pipeline requires configuring credentials and permissions before launching tasks. In an unattended runner, the agent cannot ask you for an API token or prompt you to approve a shell command.

Installing the CLI and Authenticating Providers

To install the global Cline package through npm, run:

npm i -g cline

In local development, you authenticate through an interactive setup screen:

cline auth

Inside automated runners like GitHub Actions or GitLab CI, interactive authentication is impossible. You can configure authentication non-interactively by setting your provider environment variables or passing runtime flags directly to the command:

cline -P anthropic -m claude-3-7-sonnet-20250219 -k "$ANTHROPIC_API_KEY" "verify TypeScript types"

The CLI accepts -P or --provider to declare the provider identifier, -m or --model to set the exact model string, and -k or --key to supply the API key directly for that single run.

Enabling Autonomous Tool Execution

The default behavior in Cline requires explicit human confirmation before creating files, modifying code, or running shell commands. For headless execution, you must enable auto-approval using the --auto-approve flag:

cline --auto-approve true "run npm test and fix failing unit tests in src/auth"

Setting --auto-approve true grants the agent permission to execute its file-editing tools and approved terminal commands without pausing for user input. In standard CLI runs, tool auto-approval defaults to true when a task prompt is supplied as a positional argument. Explicitly setting --auto-approve true in automation scripts guarantees unattended execution regardless of global configuration files.

Selecting Operational Modes

The Cline CLI supports two primary operational modes:

  • Act mode: The default operational mode. The agent reads context, inspects repository files, applies code edits, and executes verification commands immediately.
  • Plan mode: Activated using -p or --plan. The agent inspects code, assesses dependencies, and drafts a structured implementation strategy without modifying repository files.

In continuous integration pipelines, you can run a plan-first validation pass before permitting code modifications:

cline -p --auto-approve true "analyze database migrations in prisma/migrations and identify breaking schema changes"

Restricting Shell Commands with Permission Policies

When giving an autonomous coding agent unrestricted shell access inside a production pipeline, teams expose themselves to operational hazards. An unconstrained agent attempting to fix a test failure could accidentally execute destructive commands, alter network configurations, or delete project directories.

The Cline CLI provides an environment variable guardrail named CLINE_COMMAND_PERMISSIONS. This variable accepts a JSON string defining glob patterns for permitted and forbidden commands:

export CLINE_COMMAND_PERMISSIONS='{"allow": ["npm test", "npm run lint", "git status", "git diff"], "deny": ["rm -rf *", "sudo *", "git push --force *"], "allowRedirects": false}'

The policy schema enforces three boundaries:

  • allow: An array of glob strings defining permitted commands. When defined, any command not matching this list is blocked.
  • deny: An array of glob strings defining strictly forbidden commands. Deny rules take precedence over allow rules.
  • allowRedirects: A boolean controlling whether the agent can execute shell redirection operators like >, >>, or <. Keeping this false prevents agents from overwriting sensitive files via shell piping.

Enforcing Task Timeouts and Retries

If unattended agents enter repetitive repair loops when encountering intractable compiler errors or flaky test suites, pipeline runners can exceed job budgets. To protect pipelines, enforce a strict execution timeout:

cline --timeout 600 --retries 3 --auto-approve true "refactor legacy callback handlers in src/api"

The -t or --timeout flag sets the hard ceiling in seconds. If the task exceeds ten minutes (600 seconds), the CLI terminates the agent loop and exits. The --retries flag limits the number of consecutive failed tool calls the agent can make before halting, preventing runaway credit consumption.

How to Parse Structured JSON Output in Terminal Automation

Standard terminal text is helpful for humans, but parsing formatted terminal strings in shell scripts is fragile. ANSI color codes, progress spinners, and terminal redraws corrupt downstream text processing. Passing the --json flag forces the Cline CLI to emit newline-delimited JSON objects directly to standard output.

Understanding the JSON Event Stream

Each line emitted by Cline in JSON mode represents a discrete event object. The schema adheres to a consistent structure:

{
  "type": "say",
  "text": "All unit tests in src/auth passed successfully.",
  "ts": 1760501486669,
  "say": "text",
  "partial": false
}

The core fields in every emitted message include:

  • type: The top-level category of the event, distinguishing informational broadcasts (say) from input inquiries (ask).
  • text: The string payload containing agent explanations, tool results, or command outputs.
  • ts: A Unix timestamp in milliseconds indicating when the event occurred.
  • say: The specific subtype when type is "say", indicating whether the content is conversational text, a command execution notice, or an error description.
  • ask: The specific subtype when type is "ask", used when the agent requests permissions or clarifications.
  • reasoning: Optional chain-of-thought tokens when running models with extended reasoning enabled.
  • partial: A boolean flag indicating whether the line is a streaming token chunk (true) or a completed message block (false).

Practical JSON Parsing with jq

The downstream CI/CD stages can process this event stream in real time using jq. Here are three practical filtering patterns for automated pipelines:

Extracting completed summary statements:

cline --json --auto-approve true "audit dependencies for security advisories" | jq -r 'select(.type=="say" and .say=="text" and .partial==false) | .text'

Extracting commands executed by the agent:

cline --json --auto-approve true "run linter and fix warnings" | jq -r 'select(.say=="command") | .text'

Capturing agent reasoning steps for pipeline audit logs:

cline --json --thinking high --auto-approve true "optimize slow SQL queries in src/db" | jq -r 'select(.reasoning != null) | .reasoning' > agent_reasoning.log

Managing Pipeline Exit Codes and Failures

When managing Unix shell pipelines, the exit status of a command sequence defaults to the exit status of the final command. If you run cline | jq, your pipeline will succeed even if Cline crashed, as long as jq exited cleanly. To prevent silent failures in continuous integration jobs, configure bash pipefail:

set -eo pipefail

cline --json --auto-approve true "npm run build" > build_events.jsonl

With pipefail enabled, any non-zero exit status generated by Cline triggers an immediate failure in the calling script, stopping the pipeline before broken changes can proceed to subsequent deployment stages.

Fastio features

Automate Agent Artifact Persistence Across CI/CD Runs

Connect headless Cline pipelines to shared Fast.io workspaces with Streamable HTTP MCP tools, automatic indexing, and version history. Every organization starts with a 14-day free trial.

Steps to Build a GitHub Actions Workflow on Clean Git Branches

Running an autonomous coding agent directly against your primary branch is risky. Even with comprehensive automated tests, an unattended agent can produce subtle functional regressions or alter formatting conventions. A reliable CI/CD architecture executes headless Cline tasks on isolated, ephemeral git branches and submits pull requests for human peer review.

Branch Isolation Pattern

A secure automated workflow follows a five-stage progression:

  1. Create a clean branch: Branch off the latest target commit with a unique timestamped name.
  2. Execute headless Cline: Run the task with auto-approval, execution timeouts, and command guardrails.
  3. Verify modifications: Run static analysis, linters, and unit test suites against the modified files.
  4. Commit changes: Stage modified files and record a structured commit message detailing the agent run.
  5. Open a pull request: Push the isolated branch to the remote repository and generate a pull request using the GitHub CLI (gh pr create).

Complete GitHub Actions Workflow Definition

Use the following workflow configuration in your repository at .github/workflows/cline-automated-audit.yml:

name: Cline Automated Maintenance
on:
  workflow_dispatch:
    inputs:
      task:
        description: "Maintenance task prompt for Cline"
        required: true
        default: "Update outdated npm dependencies and ensure all test suites pass"
jobs:
  run-cline-agent:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - name: Set up Node.js Environment
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: "npm"
      - name: Install Dependencies and Cline CLI
        run: |
          npm ci
          npm i -g cline
      - name: Configure Execution Guardrails and Run Cline
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          CLINE_COMMAND_PERMISSIONS: '{"allow": ["npm *", "git *"], "deny": ["rm -rf *", "sudo *"], "allowRedirects": false}'
        run: |
          set -eo pipefail
          git config user.name "cline-bot[bot]"
          git config user.email "cline-bot@users.noreply.github.com"
          BRANCH_NAME="cline/maintenance-$(date +%Y%m%d%H%M%S)"
          git checkout -b "$BRANCH_NAME"
          cline -P anthropic -m claude-3-7-sonnet-20250219 -k "$ANTHROPIC_API_KEY" --auto-approve true --timeout 900 --json "${{ github.event.inputs.task }}" > cline_execution.jsonl
          if [[ -z $(git status --porcelain) ]]; then
            echo "No file changes produced by Cline. Exiting successfully."
            exit 0
          fi
          npm test
          npm run lint
          git add -A
          git commit -m "chore(agent): automated updates via cline headless" -m "Automated maintenance execution: ${{ github.event.inputs.task }}"
          git push origin "$BRANCH_NAME"
          gh pr create --title "Automated Maintenance: ${{ github.event.inputs.task }}" --body "Automated pull request from Cline headless execution." --base main --head "$BRANCH_NAME"

This workflow guarantees that code produced by an autonomous agent never merges directly into production branches. Human engineers retain full oversight, reviewing the generated pull request diff and automated test results before merging.

Why Autonomous Pipelines Require Persistent Context and Shared Artifacts

Running Cline in ephemeral CI/CD environments solves execution automation, but it introduces a data persistence bottleneck. When a GitHub Actions runner or GitLab CI container completes its job, the host container is destroyed. Any execution logs, architectural summaries, visual test outputs, or performance reports generated during the run vanish along with the runner disk.

Evaluating Storage Strategies for Pipeline Artifacts

Most engineering teams coordinate agent artifacts using one of three storage approaches before adopting shared cloud workspaces:

  • Ephemeral runner storage: Saving artifacts to the local runner disk works during single-job execution, but files disappear the moment the container terminates unless manually uploaded to repository release tabs.
  • Git commits: Committing execution logs, diagnostic dumps, and benchmark files directly into source repositories clutters commit histories, inflates clone sizes, and creates merge conflicts between concurrent runs.
  • Raw cloud buckets: Storing binary logs in Amazon S3 or Google Cloud Storage preserves data, but raw buckets lack semantic document search, per-file version history, and interactive collaboration features.

Fast.io as the Coordination and Persistence Layer

When connecting headless Cline workflows to an intelligent workspace like Fast.io, teams bridge the gap between ephemeral CI/CD runners and persistent team knowledge. Fast.io functions as an intelligent workspace platform where files uploaded by agents are automatically indexed for search and retrieval.

Key workspace capabilities for autonomous pipelines include:

  • Per-file version history: Every time an agent uploads an updated documentation draft, test summary, or code report, Fast.io retains complete version history. If an autonomous run introduces an error into a shared file, developers can inspect diffs and restore prior versions immediately.
  • Append-only audit log: All file uploads, reads, modifications, and downloads are tracked in a tamper-evident audit log, ensuring accountability across human and agent actions.
  • Intelligence Mode: Workspaces index uploaded markdown files, reports, and code schemas upon arrival. Once Intelligence Mode is active, team members and secondary agents can query repository context using natural language with source-backed citations.
  • Collaborative Notes: Human developers and automated agents can co-edit notes in real time. A headless pipeline can append its execution summary directly to a shared Collaborative Note while engineers monitor status.
  • Granular permissions and scoped shares: Distribute test reports and build deliverables through branded links with per-recipient access controls and automatic expiration dates.
  • Ownership transfer: An autonomous setup script can initialize an organization workspace, configure project files, and transfer primary ownership to a human engineering manager while preserving administrative credentials.

Connecting Headless Cline to Fast.io via MCP

The Cline CLI connects directly to Fast.io through the Model Context Protocol using Streamable HTTP. This standard interface allows headless agents to read existing workspace context, download reference documents, search files semantically, and upload run artifacts over an authenticated remote endpoint.

To configure Fast.io access for Cline, add the server definition to your mcp.json or cline_mcp_settings.json configuration file:

{
  "mcpServers": {
    "fastio": {
      "type": "streamableHttp",
      "url": "https://mcp.fast.io/mcp/key",
      "headers": {
        "Authorization": "Bearer your_fastio_api_token"
      },
      "disabled": false,
      "autoApprove": [
        "list_workspaces",
        "read_file",
        "upload_file",
        "search_workspace"
      ]
    }
  }
}

The connection authenticates using Bearer token authentication against https://mcp.fast.io/mcp/key. Fast.io also supports Streamable HTTP at /mcp and legacy Server-Sent Events at /sse. Adding workspace tool names to the autoApprove array ensures that the headless agent can upload artifacts and query files without blocking on manual authorization prompts.

To explore shared workspaces for autonomous development pipelines, visit the Fast.io Storage for Agents overview or view Fast.io Plans and Pricing. Creating an account is free; doing real work requires an organization on a paid subscription. Every organization starts with a 14-day free trial, which requires a credit card. | Plans are Starter at $29/mo, Business at $99/mo, and Growth at $299/mo on Fast.io pricing.

Frequently Asked Questions

How do I run Cline without a GUI or interactive prompt?

You run Cline without a graphical interface by installing the CLI via npm i -g cline and executing tasks directly from your shell. Supplying the --auto-approve true flag enables the CLI to execute file edits and shell commands non-interactively. Headless mode activates automatically whenever you pipe data into stdin, redirect stdout to a file, or pass the --json flag.

Can Cline run inside GitHub Actions?

Yes. Cline can run in GitHub Actions runners by installing the npm package globally, configuring your provider API key as an action secret, and running commands with --auto-approve true. To ensure stability, execute tasks on isolated git branches, enforce execution limits with --timeout, and submit code modifications via pull requests rather than pushing directly to default branches.

How do I enable auto-approve in Cline headless mode?

Pass the --auto-approve true flag when invoking the Cline CLI. This parameter permits the agent to create files, apply edits, and execute terminal commands without halting for human confirmation. For safety in automated environments, combine auto-approval with command whitelists using the CLINE_COMMAND_PERMISSIONS environment variable.

How do I parse structured JSON output from Cline CLI?

Pass the --json flag when running Cline to output newline-delimited JSON objects. Each line represents a message event with fields including type, text, ts, say, and partial. You can parse this stream in shell scripts using jq, such as piping to jq -r 'select(.type=="say" and .say=="text") | .text' to extract completed agent statements.

How do I prevent an autonomous headless agent from executing dangerous terminal commands?

Configure the CLINE_COMMAND_PERMISSIONS environment variable with a JSON policy containing allow and deny lists. Deny rules take precedence over allow rules. For example, setting allow to ["npm *", "git *"] and deny to ["rm -rf *", "sudo *", "git push --force *"] restricts the agent to standard development commands and blocks system-level modifications.

Related Resources

Fastio features

Automate Agent Artifact Persistence Across CI/CD Runs

Connect headless Cline pipelines to shared Fast.io workspaces with Streamable HTTP MCP tools, automatic indexing, and version history. Every organization starts with a 14-day free trial.