Complete Guide to Headless Agentic Automation

Mastering Kilo, Vibe, and Cline CLI for AI Agent Orchestration

Headless Execution

Programmatic mode activation patterns

Agent Communication

ACP protocol integration

Security Controls

Permission governance

In the rapidly evolving landscape of AI-powered development tools, three CLI-based agentic assistants have emerged as powerful platforms for automated coding workflows: Mistral Vibe, Kilo Code, and Cline. While each offers sophisticated interactive interfaces, their true potential for meta-agent orchestration lies in their headless execution capabilities—enabling AI agents to manage other AI agents through programmatic interfaces.

Primary Use Case

This guide specifically addresses the orchestration pattern where OpenCode or Kimi CLI agents manage Kilo, Vibe, and Cline as subordinate tools—a hierarchical delegation architecture that enables sophisticated multi-agent workflows while maintaining security and reliability.

Each tool supports headless automation through distinct activation patterns: Vibe via --prompt, Kilo via kilo run --auto, and Cline via -y/--json or implicit stream detection. All three offer structured JSON output, tool permission controls, and CI/CD integration, but differ in session models, security granularity, and orchestration complexity.

Quick Start

Three commands, three agents. Each runs non-interactively, emits structured output, and exits — ready to be called from a script, a CI step, or another orchestrator.

Vibe

vibe --prompt "Analyze src/" --output json

Single-shot. Auto-approves tools by default — constrain with --enabled-tools.

Kilo

kilo run --auto --json "Implement X"

Autonomous run subcommand. Pick a --mode and trust tools explicitly.

Cline

cline -y --json "Verify the change"

Headless with JSON output. Detects stdin pipes implicitly.

Chain them together

git diff origin/main | cline -y "Review" | vibe --prompt "Fix" --output json | kilo run --auto "Verify"

Each stage reads the previous stage's stdout — Unix-style composition with AI agents as the processing units.

Comparison Cheatsheet

Dimension Vibe Kilo Cline
Headless trigger--promptkilo run --auto-y / --json
Implicit activationNoneNonestdin pipe / stdout redirect
Auto-approve defaultAll tools (constrain)Respects configRequires -y
Output formatstext / json / streamingjson / json-pretty / barejson / plain text
Circuit breakers--max-turns, --max-price--timeout (exit 124)Mode flags
Tool control--enabled-tools patterns--trust-tools categoriesPermission governance
Auth env varMISTRAL_API_KEYKILO_API_KEYProvider config
Best forFast single-shot analysisAutonomous implementationVerification & review

All three support stdin piping, structured JSON output, and tool permission controls; they differ in session model, default auto-approve posture, and security granularity.

1. Architectural Foundations of Headless Agentic Execution

1.1 Core Design Principles for Non-Interactive Operation

Unix Philosophy Compliance

The three agentic CLI tools share a fundamental commitment to Unix philosophy principles: accepting instructions via stdin, processing through LLM-powered reasoning loops, and emitting results to stdout in formats suitable for downstream consumption.

# Example of stdin/stdout piping cat schema.sql | kilo run --auto "Generate migrations" | jq '.changes' > migrations.json

Agent Communication Protocol (ACP)

ACP standardizes how coding agents communicate with editors and other tools, analogous to how LSP standardized language server integration. This decouples agent reasoning from specific user interfaces.

Key Insight: ACP enables the same agent core to operate in TUI mode, IDE extension mode, or fully automated headless mode.

Session Model Trade-offs

Stateless Invocations: Simpler to reason about, easier to parallelize, more resilient to failures, but incur higher token costs due to repeated context setup.

Stateful Sessions: Preserve context across steps, reduce redundant processing, but introduce coupling between steps and require careful session lifecycle management.

1.2 Universal Activation Patterns

Tool Primary Headless Flag Implicit Activation Auto-Approve Default
Vibe --prompt "instruction" None Auto-approve all
Kilo kilo run --auto None Respects config
Cline -y / --json stdin pipe, stdout redirect Requires -y flag

Cline's Mode Detection Matrix

Explicit Autonomous:
cline -y "task" → Headless YOLO mode
Explicit Structured:
cline --json "task" → Headless JSON
Implicit Headless:
cat file | cline "task" → Plain text output
Combined:
cline -y --json "task" > output.json → Autonomous JSON

1.3 Cross-Tool Orchestration for Meta-Agent Systems

graph TD A["OpenCode/Kimi CLI
Orchestrator Agent"] --> B["Task Decomposition"] B --> C["Vibe Analysis
--prompt + --output json"] B --> D["Kilo Implementation
kilo run --auto"] B --> E["Cline Verification
-y --json"] C --> F["JSON Output Processing
jq parsing"] D --> F E --> F F --> G["Result Synthesis"] G --> H["Decision Making"] H --> I{"Quality Gates"} I -->|"Pass"| J["Deployment Pipeline"] I -->|"Fail"| K["Retry/Remediation"] K --> B style A fill:#e1f5fe style F fill:#f3e5f5 style J fill:#e8f5e8 style K fill:#fff3e0

Sequential Delegation

Orchestrator invokes one tool, processes output, then invokes the next with clear boundaries between steps.

vibe --prompt "Analyze" --output json | jq '.' > analysis.json
kilo run --auto "Implement: $(cat analysis.json)"

Parallel Delegation

Exploits process isolation for concurrent execution of independent tasks using tmux sessions.

# Multiple Cline instances in parallel
tmux split-window "cline -y task1"
tmux split-window "cline -y task2"

Conditional Delegation

Uses exit codes and output parsing for branching workflows with retry logic and fallback selection.

if kilo run --auto "task"; then
cline -y "verify"
else
vibe --prompt "diagnose"
fi

Agentic Piping Pattern

git diff origin/main | \
cline -y "Review these changes" | \
vibe --prompt "Implement fixes based on review" --output json | \
kilo run --auto "Verify fixes with tests"

This pipeline demonstrates direct tool-to-tool piping where Cline performs code review, Vibe implements fixes, and Kilo runs verification—each operating in its optimal domain with automatic handoff through stdout/stdin chaining.

2. Mistral Vibe CLI: Programmatic Mode Deep Dive

2.1 Activation and Entry Points

Primary Trigger: --prompt

The --prompt flag serves as the canonical entry point for Vibe's programmatic mode, transforming the CLI from an interactive TUI application into a single-invocation utility.

# Basic invocation
vibe --prompt "Refactor main.py for better error handling"

# With constraints
vibe --prompt "Analyze codebase" --max-turns 10 --max-price 2.00

Alternative: stdin Piping

Vibe supports stdin piping as an alternative input mechanism, eliminating shell escaping concerns with complex instructions.

# Piped input
echo "Refactor main.py" | vibe -p

# File content as prompt
cat requirements.txt | vibe --prompt "Analyze dependencies"

Default Auto-Approve Behavior

Programmatic mode automatically approves all tool calls unless constrained by --enabled-tools or agent configuration. This makes explicit tool whitelisting essential for production deployments.

# Safe: explicit tool whitelist
vibe --prompt "Task" --enabled-tools "read_file" "grep"

# Risky: all tools auto-approved
vibe --prompt "Task" # No constraints

2.2 Output Serialization and Parsing

text (default)

Human-readable plain text suitable for direct terminal display or log capture.

Analysis complete.
Found 3 security issues.
Recommend updating dependencies.

json

Complete session history as structured JSON object with tool calls and metadata.

{"messages": [
{"role": "assistant", "content": "..."},
{"role": "tool", "name": "read_file", "result": "..."}
]}

streaming

Newline-delimited JSON (NDJSON) for real-time consumption and monitoring.

{"type": "init", "timestamp": "..."}
{"type": "tool_call", "name": "grep", "args": "..."}
{"type": "result", "content": "..."}

jq Integration Patterns

Extract final response:
vibe ... --output json | jq '.messages[-1].content'
Monitor resource usage:
vibe ... --output json | jq '.usage.total_tokens'
Audit tool invocations:
vibe ... --output json | jq '.messages[] | select(.role == "tool")'
Extract cost:
vibe ... --output json | jq '.cost'

2.3 Execution Control and Circuit Breakers

--max-turns N

Hard limit on assistant reasoning turns to prevent runaway agentic loops. Each turn includes assistant response generation, tool execution, and result processing.

Recommendation: Always specify explicit turn limits for production automation based on empirical task analysis.

--max-price DOLLARS

Cost-based circuit breaker that terminates execution when cumulative API credit consumption exceeds the specified USD threshold.

# Dual protection example
vibe --prompt "Task" --max-turns 20 --max-price 5.00
Task Complexity Recommended --max-turns Typical Duration
Simple query/single file read 3-5 30-60 seconds
Multi-file analysis 5-10 1-3 minutes
Code generation with verification 10-20 3-10 minutes
Complex refactoring 20-50 10-30 minutes

--enabled-tools Pattern Syntax

Pattern-based tool whitelisting that disables all tools except those matching specified patterns.

Exact name:
read_file
Matches only read_file
Glob pattern:
bash*
Matches bash, bash_command, etc.
Regex:
re:^serena_.*$
All serena_ prefixed tools

2.4 Authentication and Environment Configuration

MISTRAL_API_KEY Environment Variable

Required Mistral API authentication configured through environment variable injection in CI/CD environments.

# GitHub Actions example
env:
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
run: vibe --prompt "Task" ...

~/.vibe/.env File Configuration

Alternative configuration through .env file in Vibe home directory, loaded on startup.

# ~/.vibe/.env
MISTRAL_API_KEY="your-api-key-here"
VIBE_HOME="/custom/config/path"
Security Note: Exclude from version control with .gitignore entry

2.5 Agentic Piping and Integration Patterns

Stateless Session Chaining

# Multi-stage analysis pipeline
vibe --prompt "Analyze API endpoints in src/" --output json | \
jq '.endpoints[] | {method, path}' | \
vibe --prompt "Generate tests for these endpoints" --output json | \
jq '.test_cases' > generated_tests.json

Chains analysis and implementation without intermediate file storage, using jq for format transformation between stages.

CI/CD Pipeline Integration

# GitHub Actions workflow step
- name: Run Vibe Analysis
env:
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
run: |
vibe --prompt "Review code for security issues" \
--max-turns 10 --max-price 2.00 \
--enabled-tools "read_file" "grep" \
--output json > vibe-results.json

Session Log Persistence

Complete session logs persisted to ~/.vibe/logs/session/ enable debugging and audit trails.

# Find and analyze recent sessions
ls -lt ~/.vibe/logs/session/ | head -5
jq '.' ~/.vibe/logs/session/session_*.json

3. Kilo Code CLI: Autonomous Mode Deep Dive

3.1 Activation and Command Structure

Primary Activation Pattern

kilo run --auto "instruction string"

The run subcommand with --auto flag enables non-interactive behavior: automatic approval, autonomous decision-making for follow-up questions, and automatic exit.

Piping Input Patterns

# Schema as input context
cat schema.sql | kilo run --auto "Generate migrations"

# Test output as context
npm test 2>&1 | kilo run --auto "Fix these test failures"

Piped content becomes available to agent tools as part of execution context, valuable for large inputs without command-line length limitations.

JSON Output Mode

# Structured JSON output
kilo run --auto --json "instruction"

# Pretty JSON for debugging
kilo run --auto --format json-pretty "instruction"

# Clean output without plugins
kilo run --auto --format json --bare "instruction"

Timeout Control

Explicit timeout specification with --timeout N (seconds) resulting in exit code 124 when exceeded.

# Timeout with specific handling
kilo run --auto --timeout 300 "Task" || {
if [ $? -eq 124 ]; then
echo "Timeout occurred, retrying with longer timeout"
kilo run --auto --timeout 600 "Task"
fi
}

3.2 Agent Mode Selection and Behavioral Profiles

Mode Behavior Tool Access Use Case
ask Read-only exploration Read tools only Analysis, review, documentation
architect Planning and design-first Read + planning tools Complex changes requiring upfront design
code Full read-write implementation All development tools Feature implementation, bug fixes
debug Diagnostic and fix-focused Analysis + fix tools Root cause analysis, test failure resolution
orchestrator Multi-agent coordination Delegation + synthesis tools Complex tasks requiring sub-agent coordination

Safe Analysis with ask Mode

# Read-only analysis for security audit
kilo run --auto --mode ask \
--trust-tools read,grep \
"Analyze codebase for security vulnerabilities"

Provides safe initial analysis phase without modification risks, suitable for automated security scanning and compliance checking.

Full Implementation with code Mode

# Full implementation with constrained permissions
kilo run --auto --mode code \
--trust-tools read,write,grep,bash \
"Implement user authentication with JWT tokens"

3.3 Tool Trust and Permission Governance

--trust-all-tools: Caution Required

Security Warning: Complete auto-approval bypass enabling arbitrary command execution.
# Use only in isolated environments
kilo run --auto --trust-all-tools "Implement feature"

Appropriate only for ephemeral development environments or tightly scoped workspaces with comprehensive output review before deployment.

--trust-tools Category Whitelist

Granular control with comma-separated list of permitted tool categories implementing default-deny security posture.

# Read-only analysis
--trust-tools read,grep

# Full development capabilities
--trust-tools read,write,grep,bash

Protected File Safeguards

Automatic protection prevents accidental modification of critical configuration and state files:

  • .kilo/ and .open-code/ directories
  • kilo.json configuration file
  • Memory Bank state files

These safeguards require external mechanisms for configuration changes rather than delegating to Kilo's agent tools.

3.4 Authentication and Organization Context

KILO_API_KEY

Overrides apiKey field in configuration file for CI/CD environments.

# Runtime injection
KILO_API_KEY="key" kilo run --auto "Task"

KILO_ORG_ID

Specifies organizational context for team billing and access control.

# Organization scoping
KILO_ORG_ID="org_123" kilo run --auto "Task"

Provider-Specific

KILOCODE_MODEL pattern for provider-specific configuration.

# Provider override
KILOCODE_MODEL="claude-3.7-sonnet" \
kilo run --auto "Task"

3.5 Operational Resilience and State Management

Exit Code Semantics

Code Meaning Action
0 Success Proceed
1 General error Log, alert
124 Timeout Retry, decompose
3 MCP startup failure Check MCP config

Stateful Session Management

# Resume specific session by UUID
kilo run --auto --resume-id a1b2c3d4-e5f6-7890-abcd-ef1234567890

# Explicit workspace scoping
kilo run --auto --workspace /path/to/project "Task"

Session UUIDs emitted in JSON output enable precise reattachment for long-running tasks spanning multiple pipeline stages.

Memory Bank Monitoring

Kilo's "Memory Bank" persists state in .kilo/ and .open-code/ directories, requiring explicit management in headless environments:

  • Preserve between invocations via volume mounts or artifact passing
  • Monitor for unexpected growth and implement cleanup policies
  • Consider encryption for sensitive information
# Check Memory Bank size
du -sh .kilo/ .open-code/

# Cleanup stale state
find .kilo/ -type f -mtime +30 -delete

4. Cline CLI: Automation Mode Deep Dive

4.1 Multi-Trigger Activation Architecture

Explicit YOLO Mode: -y / --yolo

Mandatory for Full Autonomy: Enables automatic approval of all tool calls, forces plain text output, suppresses interactive prompts.
# Basic YOLO mode
cline -y "Implement user authentication"

# Combined with JSON output
cline -y --json "Task" > output.json

Without -y flag, automation will hang on interactive prompts even in headless mode.

Implicit Activation Patterns

# Stdin pipe detection
cat file.txt | cline "Process this"

# Stdout redirection
cline "Task" > output.txt

# Both stdin and stdout
cat input | cline "Task" | grep result > output
Important: Implicit activation enables headless output formatting but does NOT enable auto-approval. Always add -y for full automation.

Complete Activation Matrix

Invocation Mode Auto-Approve Output
cline "task" Interactive TUI No ANSI-colored TUI
cline -y "task" Headless YOLO Yes Plain text
cline --json "task" Headless JSON No Structured JSON
cat file | cline "task" Headless (implicit) No Plain text
cline "task" > output Headless (implicit) No Plain text

4.2 Execution Modes: Plan vs. Act

-a / --act (Default)

Immediate tool execution based on prompt analysis. Prioritizes speed and autonomy for well-understood tasks.

Use Cases: Simple bug fixes, clear feature implementations, routine maintenance tasks.

-p / --plan

Read-only analysis and strategy formulation without executing file modifications. Produces detailed implementation plans for review.

Use Cases: Complex architectural changes, safety-critical modifications, human-reviewed implementations.

Plan-Then-Act Chaining Pattern

# Phase 1: Generate plan
cline -p --json "Implement OAuth2 authentication" > plan.json

# Phase 2: Review plan (automated or manual)
jq '.plan.steps[]' plan.json | review_tool

# Phase 3: Execute approved plan
cline -y --json "Execute this plan: $(jq -c '.plan' plan.json)"

This pattern reduces execution risk while maintaining automation velocity, enabling quality gates and human review checkpoints for critical changes.

4.3 Output Formats and Machine Readability

YOLO Mode: Plain Text Streaming

Real-time streaming of agent reasoning, tool execution descriptions, and results in human-readable plain text format.

# Real-time monitoring
cline -y "Long-running analysis" | tee cline.log | grep "PROGRESS"

# Filter for specific events
cline -y "Task" | grep -A5 "ERROR" > error-analysis.txt

JSON Mode: Complete Structured Output

Machine-parseable JSON object with complete message history, tool calls, usage metadata, and execution duration.

# Structured output processing
cline -y --json "Task" | jq '.tool_calls[].name'

# Cost and duration extraction
cline --json "Task" | jq '{cost: .cost, duration: .duration_ms}'

JSON Schema Structure

Top-Level Fields:
  • request: Original prompt and configuration
  • text: Final assistant response content
  • tool_calls: Complete tool invocation history
  • usage: Token consumption metrics
  • duration_ms: Execution time in milliseconds
Image Handling:

Binary image data (screenshots, diagrams) encoded as Base64 strings with MIME type specification for transmission through text-only channels.

"image": {
"data": "base64-string",
"mime_type": "image/png"
}

4.4 Security Sandboxing and Command Governance

CLINE_COMMAND_PERMISSIONS Environment Variable

Most granular security control with JSON string defining glob-based whitelist and blacklist patterns for shell command execution.

# Constrained autonomy pattern
CLINE_COMMAND_PERMISSIONS='{
"allow": ["npm *", "git *", "python -m pytest *"],
"deny": ["rm -rf *", "sudo *", "curl * | bash"]
}' cline -y --json "Run tests and fix failures"

Pattern Syntax Examples

Permissive patterns:
"npm *" - All npm commands
"git status" - Specific command
Restrictive patterns:
"rm -rf *" - Dangerous deletion
"sudo *" - Privilege escalation
"curl * | *sh" - Remote execution

Deny patterns take precedence over allow patterns for defense-in-depth security.

Defense-in-Depth Recommendation

Implement layered security controls for production automation:

  1. YOLO mode for automation velocity
  2. CLINE_COMMAND_PERMISSIONS for command-level restrictions
  3. Container sandboxing for filesystem isolation
  4. Network policies for egress control

No single mechanism provides sufficient protection; layered controls address both accidental errors and malicious exploitation.

4.5 Environment Isolation and Configuration

CLINE_DIR

Custom data directory isolation for multi-tenant CI systems and reproducible builds.

# Disposable execution context
CLINE_DIR=/tmp/cline-job-12345 \
cline -y "Task"

--config PATH

Explicit configuration file override for environment-specific settings.

# Environment-specific config
cline -y --config prod-config.json "Task"

XDG Compliance

Default path resolution following XDG Base Directory Specification.

# Default locations
~/.config/cline/
~/.local/share/cline/
~/.local/state/cline/logs/

MCP Lifecycle Management

Background Initialization:

MCP servers initialized in background at task startup with automatic termination on completion.

# Fail-fast MCP validation
kilo run --auto --require-mcp-startup "Task"

# Exit code 3 on MCP failure
Timeout Configuration:

Per-task timeout control including MCP initialization time in budget.

# Conservative timeout with margin
cline -y --timeout 480 "Task"

# Budget for MCP + LLM + tools

5. Cross-Cutting Concerns for Production Automation

5.1 Authentication Security in CI/CD Environments

Platform-Specific Secret Management

Platform Secret Mechanism
GitHub Actions Repository secrets + environments
secrets.MISTRAL_API_KEY
GitLab CI CI/CD variables (protected, masked)
CircleCI Contexts and project settings
Jenkins Credentials plugin

Short-Lived Credential Patterns

AWS IAM roles: OIDC federation with GitHub Actions for automatic token rotation
Azure Managed Identity: Workload identity federation for cloud-native authentication
Vault dynamic secrets: Just-in-time credential generation with AppRole or Kubernetes auth

.env File Security Requirements

# .gitignore configuration
.env
.env.local
.env.*.local
!.env.example # Template only

Additional safeguards: pre-commit hooks scanning for API key patterns, CI/CD validation failing on credential detection, and regular repository history audits.

5.2 Error Handling and Exit Code Orchestration

Shell Error Handling Foundation

# Mandatory shell configuration
#!/bin/bash
set -euo pipefail

# Error propagation with context
vibe --prompt "Task" --output json > result.json || {
echo "Vibe failed with code $?" >&2
exit 1
}

Ensures immediate pipeline halt on any failure, preventing partial execution states and masked intermediate failures.

Intelligent Retry Logic

# Retry with exponential backoff
for attempt in {1..3}; do
if cline -y "Task"; then
break
fi
sleep $((2 ** attempt))
done

Distinguish retryable failures (timeouts, rate limits) from permanent errors (authentication, permission denied).

Circuit Breaker Implementation

# State machine for failure handling
STATE="CLOSED" # Normal operation
FAILURE_COUNT=0

run_task() {
if [ "$STATE" = "OPEN" ]; then
echo "Circuit breaker open - rejecting request"
return 1
fi

if ! "$@"; then
((FAILURE_COUNT++))
if [ $FAILURE_COUNT -ge 3 ]; then
STATE="OPEN"
echo "Opening circuit breaker"
sleep 300 # Cooldown
STATE="HALF-OPEN"
fi
return 1
fi
FAILURE_COUNT=0
return 0
}

Prevents cascading failures in distributed systems by temporarily rejecting requests after failure thresholds, with automatic recovery testing.

5.3 Output Processing and Downstream Integration

Essential jq Parsing Patterns

Extract final response:
jq '.text' # Cline
jq '.messages[-1].content' # Vibe
Tool call history:
jq '.tool_calls[]' # Cline
jq '.messages[] | select(.role == "tool")' # Vibe
Usage metrics:
jq '.usage' # Universal
jq '{cost: .cost, duration: .duration_ms}'

Real-Time Stream Processing

# Live metric extraction
vibe --output streaming | \
jq --unbuffered -c 'select(.type=="tool_call")' | \
tee -a tool-metrics.jsonl | \
jq -c '{tool: .name, time: now}'

# Dashboard-compatible output
kilo --format stream-json | \
jq --unbuffered -c '{status: .type, progress: .progress}'

--unbuffered flag critical for real-time processing to prevent output buffering delays.

Log Aggregation

Structured logging to ELK/Loki/Splunk with unified field mapping.

# Unified event format
{
"source": "vibe|kilo|cline",
"job_id": "$CI_JOB_ID",
"event_type": "tool_call|completion",
"cost_usd": float,
"duration_ms": int
}

Artifact Generation

Automated commit messages, PR descriptions, and documentation.

# Generate commit message
git diff | cline -y "Write commit" \
> commit-msg.txt
git commit -F commit-msg.txt

# PR description
vibe --prompt "Review for PR" | \
jq -r '.messages[-1].content' > pr.md

Cost Monitoring

Proactive budget enforcement with automated alerting.

# Daily budget check
DAILY_BUDGET=50.00
CURRENT=$(jq -s 'map(.cost)|add' *.json)

if (( $(echo "$CURRENT > $BUDGET" | bc) )); then
echo "ALERT: Budget exceeded"
touch /var/run/budget-exceeded
fi

5.4 Observability and Debugging

Session Export and Analysis

# Export specific session
kilo export a1b2c3d4-e5f6-7890-abcd > session.json

# Extract tool call sequence
jq '.messages[] | select(.type=="tool_call") |
{tool: .name, params: .arguments}' session.json

# Compare expected vs actual
diff <(jq -s 'map(select(.type=="tool_call") | .name)' expected.jsonl) \
<(jq -s 'map(select(.type=="tool_call") | .name)' actual.jsonl)

Stream Capture and Replay

# Capture for later analysis
vibe --output streaming | \
tee capture.jsonl | \
jq -c 'select(.type=="result")'

# Replay for investigation
cat capture.jsonl | \
jq 'select(.type=="tool_call")' | less

# Automated anomaly detection
grep -c '"type":"error"' capture.jsonl

Comprehensive Audit Logging

Immutable Log Requirements:
  • Command invocation with flags (sanitized)
  • Tool execution parameters and results
  • API requests with tokens and cost
  • Session context and configuration
Retention Policies:
  • Session logs: 90 days (no sensitive content)
  • Session logs: 30 days (with code/content)
  • API bodies: 7 days (with tokenization)
  • Usage metadata: 2 years (aggregated)

6. Reference Implementations for Meta-Agent Systems

6.1 GitHub Actions Workflow Patterns

Vibe: Automated Code Review

name: Vibe Code Review
on: [pull_request]

jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Vibe
run: pip install mistral-vibe
- name: Security Review
env:
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
run: |
vibe --prompt "Review for security issues" \
--max-turns 15 --max-price 2.00 \
--enabled-tools "read_file" "grep" \
--agent plan --output json \
> vibe-review.json

Kilo: Feature Implementation

name: Kilo Feature Implementation
on: workflow_dispatch

jobs:
implement:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- name: Install Kilo
run: npm install -g @kilocode/cli
- name: Implement Feature
env:
KILO_API_KEY: ${{ secrets.KILO_API_KEY }}
KILO_ORG_ID: ${{ secrets.KILO_ORG_ID }}
run: |
kilo run --auto --mode code \
--trust-tools read,write,grep,bash \
--format json --timeout 1200 \
--workspace ${{ github.workspace }} \
"${{ github.event.inputs.feature_spec }}" \
> kilo-result.json

Multi-Tool Orchestration: Complete Workflow

name: Meta-Agent Orchestration
on: workflow_dispatch

jobs:
orchestrate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup All Tools
run: |
pip install mistral-vibe
npm install -g @kilocode/cli @cline/cli
- name: Phase 1: Vibe Analysis
env:
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
run: |
vibe --prompt "Analyze codebase for improvements" \
--max-turns 10 --max-price 1.00 --output json \
> phase1-analysis.json
- name: Phase 2: Kilo Implementation
env:
KILO_API_KEY: ${{ secrets.KILO_API_KEY }}
run: |
ANALYSIS=$(jq -r '.messages[-1].content' phase1-analysis.json)
kilo run --auto --mode architect --format json \
--trust-tools read,write,grep \
"Implement improvements: $ANALYSIS" \
> phase2-plan.json
- name: Phase 3: Cline Verification
env:
CLINE_COMMAND_PERMISSIONS: '{"allow":["npm test*","git diff"],"deny":["*"]}'
run: |
cline -y --json "Run full test suite and verify all changes" \
> phase3-verify.json
- name: Aggregate Results
run: |
jq -s '{analysis: .[0], implementation: .[1], verification: .[2]}' \
phase1-analysis.json phase2-plan.json phase3-verify.json \
> orchestration-report.json

6.2 Shell Script Automation Templates

Sequential Chaining Template

#!/bin/bash
set -euo pipefail

# Configuration
export MISTRAL_API_KEY="${MISTRAL_API_KEY:?Required}"
export KILO_API_KEY="${KILO_API_KEY:?Required}"
WORKSPACE="$(pwd)"
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
LOG_DIR="logs/${TIMESTAMP}"
mkdir -p "${LOG_DIR}"

echo "=== Phase 1: Vibe Analysis ==="
vibe --prompt "Analyze ${WORKSPACE} for code quality" \
--max-turns 15 --max-price 2.00 \
--enabled-tools "read_file" "grep" \
--agent plan --output json \
> "${LOG_DIR}/phase1-analysis.json" \
2> "${LOG_DIR}/phase1.log"

ANALYSIS="$(jq -r '.messages[-1].content' "${LOG_DIR}/phase1-analysis.json")"
echo "Analysis complete: $(wc -c <<< "${ANALYSIS}") characters"

echo "=== Phase 2: Kilo Implementation ==="
KILO_ORG_ID="${KILO_ORG_ID}" kilo run --auto \
--mode code --trust-tools read,write,grep,bash \
--format json --timeout 1800 \
--workspace "${WORKSPACE}" \
"${ANALYSIS}" \
> "${LOG_DIR}/phase2-impl.json" \
2> "${LOG_DIR}/phase2.log" || {
echo "Kilo implementation failed"
exit 1
}

echo "=== Phase 3: Cline Verification ==="
export CLINE_COMMAND_PERMISSIONS='{"allow":["npm test*","git diff"],"deny":["*"]}'
cline -y --json "Verify all changes" \
> "${LOG_DIR}/phase3-verify.json" \
2> "${LOG_DIR}/phase3.log"

echo "=== Complete ==="
echo "Results: ${LOG_DIR}/"
jq -s '{summary: {analysis: .[0].messages[-1].content[:200], impl: .[1].text[:200]}}' \
"${LOG_DIR}"/phase*.json

Parallel Execution with tmux

#!/bin/bash
set -euo pipefail

# Launch parallel Cline instances
SESSION="cline-parallel-$(date +%s)"

# Create tmux session with multiple panes
tmux new-session -d -s "${SESSION}" -n "analysis"
tmux split-window -t "${SESSION}:0"
tmux split-window -t "${SESSION}:0"
tmux select-layout -t "${SESSION}:0" tiled

# Pane 0: Security analysis
tmux send-keys -t "${SESSION}:0.0" \
'cline -y --json "Analyze for security vulnerabilities" > /tmp/cline-sec.json 2>&1; touch /tmp/cline-sec.done' C-m

# Pane 1: Performance analysis
tmux send-keys -t "${SESSION}:0.1" \
'cline -y --json "Analyze for performance bottlenecks" > /tmp/cline-perf.json 2>&1; touch /tmp/cline-perf.done' C-m

# Pane 2: Documentation check
tmux send-keys -t "${SESSION}:0.2" \
'cline -y --json "Check documentation completeness" > /tmp/cline-doc.json 2>&1; touch /tmp/cline-doc.done' C-m

# Wait for completion
for marker in /tmp/cline-*.done; do
until [[ -f "${marker}" ]]; do sleep 5; done
done

# Aggregate results
jq -s '{security: .[0], performance: .[1], documentation: .[2]}' \
/tmp/cline-sec.json /tmp/cline-perf.json /tmp/cline-doc.json

# Cleanup
tmux kill-session -t "${SESSION}"
rm -f /tmp/cline-*.json /tmp/cline-*.done

Conditional Branching with Exit Codes

#!/bin/bash
set -euo pipefail

run_with_retry() {
local max_attempts=3
local attempt=1
local timeout=300

while [[ ${attempt} -le ${max_attempts} ]]; do
echo "Attempt ${attempt}/${max_attempts}..."

if "$@"; then
return 0
fi

local exit_code=$?

# Handle specific exit codes
case $exit_code in
124) # Timeout
echo "Timeout, retrying with longer timeout"
timeout=$((timeout * 2))
;
3) # MCP failure
echo "MCP failure, attempting restart"
restart_mcp_servers
;
1) # General error
echo "Permanent failure, not retrying"
return 1
;
esac

sleep $(( 2 ** attempt ))
((attempt++))
done

return 1
}

# Main execution with branching
if run_with_retry kilo run --auto --timeout "${timeout}" "Implement feature X"; then
echo "Implementation successful, proceeding to verification"
cline -y --json "Verify implementation" > verify.json
elif [[ $? -eq 124 ]]; then
echo "Timeout occurred, decomposing task"
# Split into smaller sub-tasks...
else
echo "Implementation failed, escalating to human"
# Send alert, create ticket...
fi

6.3 Docker and Containerized Deployment

Multi-Tool Agent Image

# Multi-tool agent image
FROM node:20-slim AS base

# Install Python for Vibe
RUN apt-get update && apt-get install -y python3 python3-pip jq && rm -rf /var/lib/apt/lists/*

# Install Vibe
RUN pip3 install mistral-vibe

# Install Kilo and Cline
RUN npm install -g @kilocode/cli @cline/cli

# Create non-root user
RUN useradd -m -s /bin/bash agent
USER agent
WORKDIR /workspace

# Default: show versions
CMD echo "Vibe: $(vibe --version)" && \
echo "Kilo: $(kilo --version)" && \
echo "Cline: $(cline --version)"

Runtime Environment Injection

# Secret injection at runtime
docker run --rm \
-e MISTRAL_API_KEY="${MISTRAL_API_KEY}" \
-e KILO_API_KEY="${KILO_API_KEY}" \
-e KILO_ORG_ID="${KILO_ORG_ID}" \
-e CLINE_COMMAND_PERMISSIONS='{"allow":["npm *"],"deny":["rm -rf *"]}' \
-v "$(pwd):/workspace:ro" \
-v "/tmp/output:/output" \
agent-tools:latest \
vibe --prompt "Analyze /workspace" --output json \
> /output/analysis.json

Production Deployment with Maximum Isolation

# docker-compose.yml for isolated agent execution
version: '3.8'
services:
agent:
build: .
environment:
- MISTRAL_API_KEY=${MISTRAL_API_KEY}
- KILO_API_KEY=${KILO_API_KEY}
volumes:
- type: bind
source: ./src
target: /workspace
read_only: false
- type: volume
source: agent-state
target: /home/agent/.kilo
- type: tmpfs
target: /tmp
tmpfs:
size: 1G
working_dir: /workspace

volumes:
agent-state:

Combines network isolation, read-only source mounting, tmpfs for temporary files, and dedicated volumes for state management—providing comprehensive security boundaries for production agent execution.

7. Security Hardening and Sandboxing Best Practices

7.1 Principle of Least Privilege for Agentic Tools

Tool Whitelisting

Explicitly permit required capabilities with default-deny posture.

# Vibe example
--enabled-tools "read_file" "grep"

# Kilo example
--trust-tools read,grep
Highest Security

Command Blacklisting

Explicitly deny dangerous patterns while permitting broad categories.

# Cline example
CLINE_COMMAND_PERMISSIONS='{
"allow": ["npm *"],
"deny": ["rm -rf *", "sudo *"]
}'
Medium Security

Hybrid Approach

Combine whitelist with specific denials for defense-in-depth.

# Combined controls
--trust-tools read,write,grep
--deny-patterns "sudo *"
High Security

Filesystem Isolation Requirements

Read-Only Mounts:
# Source code read-only
docker run -v "$(pwd)/src:/workspace/src:ro" \
-v "$(pwd)/out:/workspace/out:rw" \
agent-tools "Analyze src, write to out/"
Temporary Workspaces:
# Ephemeral workspace per execution
WORKSPACE=$(mktemp -d)
trap 'rm -rf "${WORKSPACE}"' EXIT
git clone "${REPO_URL}" "${WORKSPACE}/repo"

7.2 Network and Egress Control

API Endpoint Allowlisting

Service Endpoint Pattern
Mistral API api.mistral.ai
Kilo API api.kilocode.ai
Anthropic API api.anthropic.com
OpenAI API api.openai.com

Implement DNS-level filtering or proxy configuration to block all other egress traffic.

Outbound Traffic Monitoring

# iptables-based egress filtering
iptables -A OUTPUT -p tcp -d api.mistral.ai --dport 443 -j ACCEPT
iptables -A OUTPUT -p tcp -d api.kilocode.ai --dport 443 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 443 -j LOG --log-prefix "BLOCKED_HTTPS: "
iptables -A OUTPUT -p tcp --dport 443 -j DROP

# Monitor blocked attempts
tail -f /var/log/kern.log | grep BLOCKED_HTTPS

Credential Scope Limitation

CI/CD Injection

Lifetime: Job duration (minutes)

Rotation: Every execution

Session Tokens

Lifetime: Hours

Rotation: Daily

Fallback API Keys

Lifetime: 90 days max

Rotation: Monthly automated

7.3 Input Validation and Prompt Injection Defense

Untrusted Input Sanitization

# Dangerous: direct inclusion
BAD: vibe --prompt "Fix: $(cat untrusted-file.txt)"

# Safer: structured extraction
EXTRACTED=$(jq -r '.validated_field' < trusted-json-source)
vibe --prompt "Fix: ${EXTRACTED:0:1000}" # Length limit

All tool outputs must be sanitized before reuse in subsequent prompts to prevent prompt injection attacks.

Downstream Action Verification

# Verify proposed changes match intent
ORIGINAL_INTENT="Refactor authentication module"
PROPOSED_CHANGES=$(jq -r '.plan.changes[]' plan.json)

for change in "${PROPOSED_CHANGES[@]}"; do
if [[ ! "${change}" =~ "auth" ]]; then
echo "WARNING: Change '${change}' may not match intent"
# Require explicit approval
fi
done

Context Window Hygiene

Reinforce constraints at critical decision points through prompt engineering:

# Inject constraint reminders
vibe --prompt "
${ORIGINAL_TASK}

CRITICAL CONSTRAINTS:
- Do not modify files outside src/
- Do not execute commands with 'sudo' or 'rm -rf'
- Do not commit or push changes
- All changes must be in a single commit-ready patch
" --enabled-tools "read_file" "write_file" "grep"

Constraint reinforcement becomes increasingly important with larger context windows and multi-turn interactions.

7.4 Audit and Compliance

Immutable Audit Logs

Append-only logging with cryptographic integrity verification.

Command invocations: Sanitized flags
Tool executions: Parameters and results
API requests: Tokens and cost
Session context: Configuration and ID
Retention: 2 years

Cost Monitoring

Proactive budget enforcement with automated alerting.

# Daily budget check
DAILY_BUDGET=50.00
CURRENT=$(jq -s 'map(.cost)|add' *.json)

if (( $(echo "$CURRENT > $BUDGET" | bc) )); then
echo "ALERT: Budget exceeded"
touch /var/run/budget-exceeded
fi

Data Retention

Automated enforcement with audit trails of deletion actions.

Session logs: 90 days (no sensitive content)
Session logs: 30 days (with code/content)
API bodies: 7 days (with tokenization)
Usage metadata: 2 years (aggregated)

Compliance Framework Integration

SOC 2 / ISO 27001 Requirements:
  • Complete audit trails of all agent actions
  • Access control and permission management
  • Data encryption in transit and at rest
  • Regular security assessments and penetration testing
HIPAA / GDPR Considerations:
  • Data minimization and purpose limitation
  • Right to erasure implementation
  • Data portability support
  • Consent management for data processing

FAQ

Which agent should I pick first?

Match the agent to the step: Vibe for fast single-shot analysis, Kilo for autonomous implementation, Cline for verification. Most production pipelines chain more than one.

How do I keep a runaway agent from spending too much?

Set explicit limits: Vibe's --max-turns and --max-price, and Kilo's --timeout (which exits 124 when exceeded). Pair them with default-deny tool trust so the agent cannot escalate beyond its scope.

Should I auto-approve all tools in production?

No. Prefer a default-deny posture: whitelist only the tool categories each task needs (Vibe --enabled-tools, Kilo --trust-tools). Reserve --trust-all-tools for ephemeral, isolated environments with output review before deploy.

How do agents hand results to each other?

Through stdout/stdin piping with jq reshaping between stages. Emit JSON output from each agent and parse the fields the next stage needs — the same Unix composition model, with agents as the processing units.

Is headless mode safe for production?

Yes, with guardrails: least-privilege tool trust, isolated execution environments, explicit turn/cost/time limits, structured output review, and audit logs. Never let an unattended agent push to production without a quality gate and human review of the diff.