# Agent Teams Source: https://docs.airun.me/advanced/agent-teams Run multiple Claude instances collaborating on shared tasks with internal coordination ## What Are Agent Teams? Agent Teams enable multiple Claude instances to collaborate on shared tasks, with one session acting as the lead coordinator and spawning teammates to work in parallel. This is an **experimental feature** built into Claude Code that AI Runner exposes through the `--team` flag. **Key characteristics:** * One lead agent coordinates the work * Teammates are spawned as needed for parallel execution * Coordination uses Claude Code's internal task list and mailbox (not provider-specific) * Works with **all providers** — AWS, Vertex, Ollama, Vercel, etc. * **Interactive mode only** — not supported in shebang/piped script modes ## Quick Start ```bash theme={null} # Enable agent teams with default provider ai --team # Combine with any provider ai --aws --opus --team ai --ollama --team ai --vercel --model xai/grok-code-fast-1 --team # Control teammate display mode ai --team --teammate-mode tmux # Split panes via tmux ai --team --teammate-mode auto # Automatic display (default) ``` ## How It Works Agent Teams leverage Claude Code's internal coordination system: 1. **Lead Agent**: The main session you interact with 2. **Task List**: Shared work queue managed by the lead 3. **Mailbox**: Inter-agent communication channel 4. **Teammates**: Spawned workers that execute tasks and report back The lead agent breaks down complex tasks, delegates work to teammates, and synthesizes results. All coordination happens through Claude Code's internal mechanisms — there's no provider-specific orchestration. ```bash theme={null} # Example: Complex multi-file refactoring ai --aws --opus --team # > "Refactor the authentication system across all modules" # # Lead: I'll coordinate this refactoring across 5 modules # Teammate 1: Working on auth/login.ts # Teammate 2: Working on auth/session.ts # Teammate 3: Working on middleware/auth.ts # Lead: Reviewing changes and ensuring consistency... ``` ## Flags and Options ### `--team` Flag **AI Runner flag** that enables agent teams by setting the `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` environment variable. ```bash theme={null} ai --team # Enable teams ai --aws --opus --team # Teams with specific provider ``` ### `--teammate-mode` Flag **Claude Code native flag** (passed through by AI Runner) that controls how teammates are displayed: | Mode | Behavior | | ------------ | ---------------------------------------------------------------------- | | `auto` | Automatic display (default) — Claude Code chooses based on environment | | `in-process` | Teammates share the same terminal output | | `tmux` | Each teammate gets its own tmux split pane | ```bash theme={null} ai --team --teammate-mode tmux # Split panes ai --team --teammate-mode in-process # Shared terminal ``` **Note:** `--teammate-mode` without `--team` has no effect (teammates aren't spawned). ## Limitations ### Interactive Mode Only Agent teams require an interactive session. Scripts (shebang/piped) run in single-agent mode: ```bash theme={null} # ✅ Works — interactive session ai --team # ❌ Ignored — script mode ai --team task.md # --team ignored, warning shown ./task.md # --team in shebang ignored ``` If you specify `--team` in a script, AI Runner shows a warning and disables it: ``` [AI Runner] Warning: Agent teams (--team) requires interactive mode. Ignoring flag. ``` ### Token Scaling Each teammate consumes tokens independently. Token usage scales roughly linearly with the number of active teammates: * **1 teammate active**: \~1× normal token usage * **3 teammates active**: \~3× normal token usage * **5 teammates active**: \~5× normal token usage The lead agent coordinates work to minimize redundant operations, but parallel execution inherently uses more tokens than sequential work. **Cost implications:** * More teammates = faster completion but higher cost * The lead agent spawns teammates as needed (not all at once) * Simple tasks may not spawn teammates at all ### Provider Compatibility Agent teams work with **all providers** because coordination is internal to Claude Code: ```bash theme={null} # All supported ai --aws --team ai --vertex --team ai --apikey --team ai --ollama --team ai --lmstudio --team ai --vercel --team ai --azure --team ``` The provider's API sees individual requests from each agent (lead + teammates). From the provider's perspective, it's just multiple concurrent sessions. ## Use Cases ### Parallel File Operations Refactoring, migration, or analysis across multiple files: ```bash theme={null} ai --team # > "Update all React components to use TypeScript strict mode" ``` Teammates work on different files simultaneously while the lead ensures consistency. ### Complex Multi-Step Tasks Tasks with independent subtasks: ```bash theme={null} ai --aws --opus --team # > "Set up CI/CD: configure GitHub Actions, add Docker support, # write deployment docs, and set up monitoring" ``` Each teammate handles one aspect while the lead coordinates. ### Large Codebase Analysis Investigating patterns across many files: ```bash theme={null} ai --team # > "Find all database queries and check for SQL injection vulnerabilities" ``` Teammates scan different modules in parallel. ## Saving Team Mode as Default Use `--set-default` to persist your team configuration: ```bash theme={null} # Save AWS + Opus + Teams as default ai --aws --opus --team --set-default # Now 'ai' uses teams by default ai # Launches with --aws --opus --team # Clear saved defaults ai --clear-default ``` ## Troubleshooting ### Teams Not Spawning If you enable `--team` but don't see teammates: 1. **Check mode**: Teams only work in interactive sessions, not scripts 2. **Task complexity**: Simple tasks may not need teammates 3. **Environment**: Run `ai-status` to verify `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` is set ### Tmux Mode Not Working If `--teammate-mode tmux` doesn't split panes: 1. **Tmux installed**: `which tmux` should return a path 2. **Inside tmux**: The flag only works when already in a tmux session 3. **Fallback**: Claude Code falls back to `in-process` if tmux unavailable ### High Token Usage If you're seeing unexpectedly high token consumption: 1. **Multiple teammates**: Check how many teammates are active (scales linearly) 2. **Use smaller model for teammates**: Override the small/fast model in `~/.ai-runner/secrets.sh`: ```bash theme={null} export CLAUDE_SMALL_FAST_MODEL_AWS="us.anthropic.claude-haiku-4-5-20251001-v1:0" ``` 3. **Disable teams**: Remove `--team` if parallel execution isn't needed ## Related Documentation * [Claude Code Agent Teams](https://code.claude.com/docs/en/agent-teams) — Official Claude Code documentation * [Configuration](/advanced/configuration) — Model overrides and dual model system * [AI Command](/cli/ai) — Core interactive mode features # Composable Scripts Source: https://docs.airun.me/advanced/composable-scripts Advanced patterns for chaining AI scripts, dispatcher workflows, and process isolation ## Overview Composable scripts let you build complex AI workflows from simple, reusable pieces. Chain scripts together like Unix commands, use dispatchers to orchestrate tool access, and leverage process isolation for clean multi-step pipelines. ## The `--cc` Flag `--cc` is shorthand for `--tool cc`, which explicitly selects Claude Code as the backend tool. Since Claude Code is currently the only supported tool, `--cc` has no effect on its own — but it becomes meaningful when combined with other flags. ```bash theme={null} ai task.md # Auto-detects tool (Claude Code) ai --cc task.md # Explicit tool selection (same result) ``` **Key point:** `--cc` alone does NOT grant tool access. You need `--skip` or `--bypass` for that. ## The Dispatcher Pattern Use `--cc --skip` to give the AI full access to Claude Code's tools (shell commands, file operations, browser automation) during script execution. This creates a **dispatcher** — a script that can take real actions: ```markdown theme={null} #!/usr/bin/env -S ai --cc --skip --live Analyze the codebase, run the test suite, and fix any failures. Print a summary after each step. ``` ### Why `--cc --skip`? * **`--cc`**: Selects Claude Code as the tool (explicit, for future compatibility) * **`--skip`**: Shorthand for `--dangerously-skip-permissions` (grants full tool access) * **`--live`**: Streams progress narration in real-time The AI can now: * Run shell commands (`npm test`, `git status`, etc.) * Read and write files * Browse the web with `--chrome` * Use all Claude Code tools without permission prompts ### Example: Test Runner Dispatcher ```markdown theme={null} #!/usr/bin/env -S ai --cc --skip --live --- vars: suite: all --- Run the {{suite}} test suite. If failures occur, analyze logs and attempt fixes. After each action, print a brief status update. ``` ```bash theme={null} chmod +x run-tests.md ./run-tests.md # Run all tests ./run-tests.md --suite integration # Run integration tests only ``` ### Tradeoff: Tool Output Visibility When Claude Code runs shell commands, subprocess output is captured internally (not streamed to your terminal). You won't see live `npm test` output scrolling by. **Solution:** Use `--live` and prompt the AI to narrate progress: ```markdown theme={null} #!/usr/bin/env -S ai --cc --skip --live Run the test suite. After running the command, tell me how many tests passed/failed before proceeding to the next step. ``` This gives you visibility into what's happening through the AI's narration. ## Chaining Scripts Together Connect scripts in Unix pipelines. Each script runs independently with clean process isolation: ```bash theme={null} ./parse-logs.md | ./analyze-errors.md | ./generate-report.md > report.txt ``` ### Process Isolation AI Runner clears inherited environment variables between nested calls so each script starts fresh: ```bash theme={null} # setup.sh wrapper script #!/bin/bash ./configure.md && ./deploy.md && ./test.md ``` Each `.md` script runs in isolation: * No inherited `ANTHROPIC_MODEL` or `ANTHROPIC_SMALL_FAST_MODEL` * No carried-over provider configuration (`CLAUDE_CODE_USE_BEDROCK`, etc.) * No leaked session IDs or internal state This prevents state leakage and ensures each script behaves identically whether run standalone or as part of a pipeline. ### Child Scripts Should Be Simple **Best practice:** Only the top-level dispatcher should use `--cc`. Child scripts in pipelines should be simple prompt mode: ```bash theme={null} # ✅ Good: Dispatcher calls simple scripts ./dispatcher.md # Uses --cc --skip ↳ calls: ./analyze.md | ./format.md # No --cc, pure prompt processing # ❌ Avoid: Nested tool access ./script1.md # Uses --cc --skip ↳ calls: ./script2.md # Also uses --cc --skip # Complexity explosion ``` Why? Nested tool access creates complexity: * Multiple agentic loops * Unpredictable execution order * Debugging nightmares Keep child scripts pure: input → processing → output. ### Example: Multi-Stage Pipeline **dispatcher.md** (top-level orchestrator): ```markdown theme={null} #!/usr/bin/env -S ai --cc --skip --live Run the following pipeline: 1. Extract error patterns from logs: `cat logs/*.txt | ./extract-errors.md` 2. Analyze patterns: `./analyze-patterns.md` 3. Generate report: `./generate-report.md > report.md` Print status after each stage. ``` **extract-errors.md** (simple filter): ```markdown theme={null} #!/usr/bin/env ai Read the log data from stdin. Extract all ERROR and FATAL entries. Output as JSON: [{"timestamp": "...", "message": "..."}] ``` **analyze-patterns.md** (simple analysis): ```markdown theme={null} #!/usr/bin/env ai Read error JSON from stdin. Identify the 3 most common error types. Output summary text. ``` **generate-report.md** (simple formatter): ```markdown theme={null} #!/usr/bin/env ai Read analysis from stdin. Format as a markdown report with: - Executive summary - Top error types - Recommended fixes ``` Run the pipeline: ```bash theme={null} ./dispatcher.md ``` ## Long-Running Scripts Scripts that take more than 30 seconds (browser automation, multi-step analysis, CI/CD pipelines) should always use `--live`: ```markdown theme={null} #!/usr/bin/env -S ai --skip --chrome --live Navigate to the app, run the full test suite, and report results. Narrate each step as you go. ``` ### Why `--live` Matters **Without `--live`:** * No output until the entire script completes * No indication of progress * Looks frozen for minutes **With `--live`:** * Heartbeat while waiting for first response * Real-time narration of progress * Immediate feedback on what's happening ### Streaming at Turn Granularity `--live` streams **between tool calls**, not during them. The AI's text responses appear immediately, but tool execution (shell commands, file writes) completes before streaming continues. **Prompt for narration:** ```markdown theme={null} #!/usr/bin/env -S ai --skip --live Run the build. After the build completes, tell me if it succeeded. Then run tests. After tests complete, summarize results. Print status updates between each step. ``` Phrases like **"print as you go"**, **"after each step"**, or **"tell me when done"** prompt the AI to write text between tool calls, giving `--live` something to stream. ## Output Redirection with `--live` When stdout is redirected, `--live` separates narration from content: ```bash theme={null} ./generate-report.md > report.md ``` **Console (stderr):** ``` [AI Runner] Using: Claude Code + AWS Bedrock [AI Runner] Model: global.anthropic.claude-sonnet-4-6 Analyzing repository structure... Examining core modules... Generating report... [AI Runner] Done (150 lines written) ``` **File (stdout):** ```markdown theme={null} # Repository Analysis Clean report content without status messages... ``` How it works: 1. Intermediate turns (narration) stream to **stderr** 2. The final turn is split at the first content marker (`---` frontmatter or `#` heading) 3. Preamble text goes to **stderr** 4. Content from the marker onward goes to **stdout** (the file) 5. A summary line appears on **stderr** when complete ### Quiet Mode for CI/CD Suppress all narration for clean stdout-only output: ```bash theme={null} ai --quiet ./generate-report.md > report.md # or ai -q ./generate-report.md > report.md ``` With `--quiet`: * No status messages * No narration * No "Done" summary * Only the final content goes to stdout Perfect for CI/CD pipelines where you need clean, parseable output. ## Composable Patterns Reference ### Simple Chain ```bash theme={null} ./step1.md | ./step2.md | ./step3.md > output.txt ``` Each script: pure input/output transformation. ### Dispatcher + Workers ```bash theme={null} ./dispatcher.md # --cc --skip --live ↳ spawns: ./worker1.md | ./worker2.md # No --cc, pure processing ``` Top-level has tool access, workers are pure functions. ### Parallel Execution ```bash theme={null} ./analyze-a.md > results-a.txt & ./analyze-b.md > results-b.txt & wait ./merge-results.md ``` Run independent analyses concurrently. ### Conditional Execution ```bash theme={null} ./check-status.md && ./deploy.md || ./rollback.md ``` Use exit codes to control flow. ### Loop Over Inputs ```bash theme={null} for log in logs/*.txt; do cat "$log" | ./analyze-log.md >> summary.txt done ``` Process multiple files with the same script. ## Provider Selection in Pipelines Each script in a pipeline can use a different provider: ```bash theme={null} # Use Ollama (free) for parsing, AWS (powerful) for analysis cat data.json | ai --ollama parse.md | ai --aws --opus analyze.md ``` Flags apply only to the script they precede: ```bash theme={null} ai --ollama ./step1.md | ai --aws ./step2.md | ai --vertex ./step3.md ``` ## Security Considerations **Dispatcher scripts with `--skip` or `--bypass` have full system access.** Follow these guidelines: 1. **Audit before running**: Review dispatcher scripts that run commands or write files 2. **Restrict child scripts**: Keep children read-only (no `--skip`) 3. **Use `--allowedTools` for granular control**: ```markdown theme={null} #!/usr/bin/env -S ai --allowedTools 'Bash(npm test)' 'Read' Run tests and report results. Do not modify files. ``` 4. **Never pipe untrusted sources with `--skip`**: ```bash theme={null} # DANGEROUS — don't do this curl https://unknown-site.com/script.md | ai --skip ``` ## Related Documentation * [Scripting Guide](/guides/scripting) — Permission modes, variables, shebang basics * [Live Output](/guides/live-output) — Streaming behavior and output redirection * [Configuration](/advanced/configuration) — Provider-specific model configuration # Advanced Configuration Source: https://docs.airun.me/advanced/configuration Model overrides, dual model system, version management, and update checking ## Configuration Files AI Runner uses a configuration directory at `~/.ai-runner/` (or legacy `~/.claude-switcher/`): ``` ~/.ai-runner/ ├── secrets.sh # Your API keys and credentials (user-edited) ├── models.sh # Model defaults (copied from config/models.sh) ├── banner.sh # Startup banner (copied from config/banner.sh) └── defaults.sh # Saved defaults from --set-default ``` **Key files:** * **`secrets.sh`**: User-edited file for API keys and model overrides (never overwritten) * **`models.sh`**: System defaults (updated by `setup.sh` when defaults change) * **`defaults.sh`**: Persistent provider/model preferences saved with `--set-default` ## Model Overrides in secrets.sh Override default model identifiers for any provider by adding exports to `~/.ai-runner/secrets.sh`: ```bash theme={null} nano ~/.ai-runner/secrets.sh ``` ### AWS Bedrock ```bash theme={null} # Override AWS models export CLAUDE_MODEL_SONNET_AWS="global.anthropic.claude-sonnet-4-6" export CLAUDE_MODEL_OPUS_AWS="global.anthropic.claude-opus-4-6-v1" export CLAUDE_MODEL_HAIKU_AWS="us.anthropic.claude-haiku-4-5-20251001-v1:0" # Override small/fast model for background operations export CLAUDE_SMALL_FAST_MODEL_AWS="us.anthropic.claude-haiku-4-5-20251001-v1:0" ``` Pin a specific dated version: ```bash theme={null} export CLAUDE_MODEL_OPUS_AWS="global.anthropic.claude-opus-4-6-20260205" ``` ### Google Vertex AI ```bash theme={null} export CLAUDE_MODEL_SONNET_VERTEX="claude-sonnet-4-6" export CLAUDE_MODEL_OPUS_VERTEX="claude-opus-4-6" export CLAUDE_MODEL_HAIKU_VERTEX="claude-haiku-4-5@20251001" export CLAUDE_SMALL_FAST_MODEL_VERTEX="claude-haiku-4-5@20251001" ``` ### Anthropic API ```bash theme={null} export CLAUDE_MODEL_SONNET_ANTHROPIC="claude-sonnet-4-6" export CLAUDE_MODEL_OPUS_ANTHROPIC="claude-opus-4-6" export CLAUDE_MODEL_HAIKU_ANTHROPIC="claude-haiku-4-5" export CLAUDE_SMALL_FAST_MODEL_ANTHROPIC="claude-haiku-4-5" ``` ### Microsoft Azure Model names are deployment names from your Azure portal: ```bash theme={null} export CLAUDE_MODEL_SONNET_AZURE="claude-sonnet-4-6" export CLAUDE_MODEL_OPUS_AZURE="claude-opus-4-6" export CLAUDE_MODEL_HAIKU_AZURE="claude-haiku-4-5" export CLAUDE_SMALL_FAST_MODEL_AZURE="claude-haiku-4-5" ``` ### Vercel AI Gateway Use `provider/model` format (dots not dashes in version numbers): ```bash theme={null} export CLAUDE_MODEL_SONNET_VERCEL="anthropic/claude-sonnet-4.6" export CLAUDE_MODEL_OPUS_VERCEL="anthropic/claude-opus-4.6" export CLAUDE_MODEL_HAIKU_VERCEL="anthropic/claude-haiku-4.5" export CLAUDE_SMALL_FAST_MODEL_VERCEL="anthropic/claude-haiku-4.5" ``` Non-Anthropic models: ```bash theme={null} export CLAUDE_MODEL_SONNET_VERCEL="xai/grok-code-fast-1" export CLAUDE_SMALL_FAST_MODEL_VERCEL="xai/grok-code-fast-1" ``` ### Ollama (Local + Cloud) By default, AI Runner auto-detects available models. Override with: ```bash theme={null} # Local models (requires 24GB+ VRAM) export OLLAMA_MODEL_HIGH="qwen3:72b" # For --opus/--high export OLLAMA_MODEL_MID="qwen3-coder" # For --sonnet/--mid export OLLAMA_MODEL_LOW="gemma3" # For --haiku/--low # Cloud models (no GPU required, 198K context) export OLLAMA_MODEL_HIGH="minimax-m2.5:cloud" # 80% SWE-bench export OLLAMA_MODEL_MID="glm-5:cloud" # 78% SWE-bench export OLLAMA_MODEL_LOW="glm-5:cloud" # Background model (optional, defaults to same as MID) export OLLAMA_SMALL_FAST_MODEL="gemma3" ``` ### LM Studio (Local) By default, AI Runner uses the first loaded model for all tiers. Override: ```bash theme={null} export LMSTUDIO_HOST="http://localhost:1234" export LMSTUDIO_MODEL_HIGH="openai/gpt-oss-20b" export LMSTUDIO_MODEL_MID="openai/gpt-oss-20b" export LMSTUDIO_MODEL_LOW="ibm/granite-4-micro" ``` ## Dual Model System Claude Code uses **two models** for optimal performance and cost: ### 1. Primary Model (`ANTHROPIC_MODEL`) The main model you interact with. Set by your tier flags: ```bash theme={null} ai --opus task.md # Uses CLAUDE_MODEL_OPUS_ ai --sonnet task.md # Uses CLAUDE_MODEL_SONNET_ ai --haiku task.md # Uses CLAUDE_MODEL_HAIKU_ ai --model custom-id # Uses custom-id directly ``` Used for: * Main conversation * Complex reasoning * User-facing responses ### 2. Small/Fast Model (`ANTHROPIC_SMALL_FAST_MODEL`) The background/auxiliary model for lightweight operations. Automatically set based on provider: ```bash theme={null} # From config/models.sh defaults: export CLAUDE_SMALL_FAST_MODEL_AWS="${CLAUDE_MODEL_HAIKU_AWS}" export CLAUDE_SMALL_FAST_MODEL_VERTEX="${CLAUDE_MODEL_HAIKU_VERTEX}" export CLAUDE_SMALL_FAST_MODEL_ANTHROPIC="${CLAUDE_MODEL_HAIKU_ANTHROPIC}" # ... etc for each provider ``` Used for: * Sub-agents and teammates (with `--team`) * File operations and analysis * Quick auxiliary tasks * Background work that doesn't need the full model **Cost savings:** Using Haiku for background operations while running Opus for main work reduces costs without sacrificing quality for complex reasoning. ### How It's Applied When you run `ai --aws --opus`, the scripts set: ```bash theme={null} export ANTHROPIC_MODEL="global.anthropic.claude-opus-4-6-v1" # Primary export ANTHROPIC_SMALL_FAST_MODEL="us.anthropic.claude-haiku-4-5-..." # Background ``` Claude Code automatically uses the appropriate model for each operation. ### Overriding the Small/Fast Model Customize in `~/.ai-runner/secrets.sh`: ```bash theme={null} # Use Sonnet instead of Haiku for background work export CLAUDE_SMALL_FAST_MODEL_AWS="global.anthropic.claude-sonnet-4-6" # Use same model for both (consistency over cost) export CLAUDE_SMALL_FAST_MODEL_AWS="${CLAUDE_MODEL_OPUS_AWS}" ``` **When to override:** * **Agent teams**: Higher-quality teammates with `--team` * **Complex file operations**: Better analysis with Sonnet background model * **Consistency**: Same model for all operations (disable two-model system) ## Persistent Defaults Save your preferred provider and model combination: ```bash theme={null} # Set default ai --aws --opus --set-default # Now 'ai' uses AWS + Opus by default ai # Uses saved defaults ai task.md # Uses saved defaults # Override saved defaults ai --vertex task.md # Uses Vertex instead ai --haiku task.md # Uses Haiku instead # Clear saved defaults ai --clear-default ``` **What gets saved** (`~/.ai-runner/defaults.sh`): ```bash theme={null} AI_DEFAULT_PROVIDER="aws" AI_DEFAULT_MODEL_TIER="high" # From --opus AI_DEFAULT_CUSTOM_MODEL="" # From --model (if used) AI_DEFAULT_TEAM_MODE="enabled" # From --team (if used) AI_DEFAULT_TEAMMATE_MODE="tmux" # From --teammate-mode (if used) ``` **Precedence** (highest to lowest): 1. CLI flags: `ai --vertex task.md` 2. Shebang flags: `#!/usr/bin/env -S ai --aws` 3. Saved defaults: `--set-default` 4. Auto-detection: Current Claude subscription ## Model Configuration Files ### `config/models.sh` (System Defaults) Shipped with AI Runner, defines default model IDs for each provider: ```bash theme={null} # AWS Bedrock defaults export CLAUDE_MODEL_SONNET_AWS="global.anthropic.claude-sonnet-4-6" export CLAUDE_MODEL_OPUS_AWS="global.anthropic.claude-opus-4-6-v1" export CLAUDE_MODEL_HAIKU_AWS="us.anthropic.claude-haiku-4-5-20251001-v1:0" # Small/fast model defaults export CLAUDE_SMALL_FAST_MODEL_AWS="${CLAUDE_MODEL_HAIKU_AWS}" ``` These ship with AI Runner and are updated when new model versions are released. ### `~/.ai-runner/models.sh` (User Copy) Copied from `config/models.sh` during `setup.sh`. Updated when system defaults change: ```bash theme={null} ./setup.sh # Model configuration has been updated. # Changes include updated default model versions. # Update to latest model defaults? [Y/n]: ``` **When to update:** * After `git pull` if model defaults changed * To get new model versions (e.g., Opus 4.6 → Opus 4.7) * If your models aren't working (outdated IDs) **When to keep:** * You have custom overrides in `secrets.sh` (they take precedence) * You want to pin specific versions ### Override Hierarchy ``` secrets.sh overrides ← Highest priority (user customization) ↓ ~/.ai-runner/models.sh ← Middle (user's copy of defaults) ↓ config/models.sh ← Lowest (system defaults, read-only) ``` Example: ```bash theme={null} # config/models.sh (system default) export CLAUDE_MODEL_OPUS_AWS="global.anthropic.claude-opus-4-6-v1" # User runs: ai --aws --opus # Uses: global.anthropic.claude-opus-4-6-v1 # User adds to secrets.sh: export CLAUDE_MODEL_OPUS_AWS="global.anthropic.claude-opus-4-6-20260205" # Now: ai --aws --opus # Uses: global.anthropic.claude-opus-4-6-20260205 (override wins) ``` ## Version File and Update Checking AI Runner includes automatic update checking with smart caching. ### Version File (`VERSION`) Shipped with AI Runner, defines the current version: ```bash theme={null} cat VERSION # v2.1.0 ``` References: * Installed to: `/usr/local/share/ai-runner/VERSION` * Used by: `ai --version`, `ai-status`, update checker ### Update Checking AI Runner checks for updates once every 24 hours (non-blocking): ```bash theme={null} ai # Shows update notice if available ai-status # Shows update status ``` **How it works:** 1. **Cache-only check** (runs in background on startup): * Queries GitHub API for latest release * Compares with installed version * Caches result for 24 hours * Never blocks startup 2. **Notice display** (if update available): ``` [AI Runner] Update available: v2.1.0 → v2.2.0 [AI Runner] Run 'ai update' to upgrade ``` 3. **Manual update:** ```bash theme={null} ai update # Fetching latest version from andisearch/airun... # Current: v2.1.0 # Latest: v2.2.0 # Update available. Proceed? [Y/n]: ``` ### Disabling Update Checks Add to your shell profile: ```bash theme={null} export AI_NO_UPDATE_CHECK=1 ``` Reload: ```bash theme={null} source ~/.bashrc # or ~/.zshrc ``` ### Update Cache Location Update check results are cached at: ``` ~/.ai-runner/.update-cache ``` **Cache format:** ```bash theme={null} cat ~/.ai-runner/.update-cache # LAST_CHECK=1735689600 # LATEST_VERSION=v2.2.0 # UPDATE_AVAILABLE=true ``` Cache expires after 24 hours (86400 seconds). ### Manual Update (Without `ai update`) If you prefer manual updates: ```bash theme={null} cd ~/path/to/airun # Your cloned repo git pull ./setup.sh ``` This preserves your `secrets.sh` and prompts about updating `models.sh`. ## Environment Variables Reference ### Runtime Variables (Set by AI Runner) | Variable | Purpose | Set By | | -------------------------------------- | --------------------------- | ----------------------------------------------------------------- | | `ANTHROPIC_MODEL` | Primary model for main work | Provider scripts based on `--opus`/`--sonnet`/`--haiku`/`--model` | | `ANTHROPIC_SMALL_FAST_MODEL` | Background/auxiliary model | Provider scripts from `CLAUDE_SMALL_FAST_MODEL_` | | `ANTHROPIC_BASE_URL` | API endpoint | Provider scripts (Ollama, LM Studio, Vercel) | | `ANTHROPIC_AUTH_TOKEN` | Bearer token auth | Provider scripts (Vercel) | | `CLAUDE_CODE_USE_BEDROCK` | Enable AWS Bedrock mode | AWS provider | | `CLAUDE_CODE_USE_VERTEX` | Enable Vertex AI mode | Vertex provider | | `CLAUDE_CODE_USE_FOUNDRY` | Enable Azure Foundry mode | Azure provider | | `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` | Enable agent teams | `--team` flag | | `AI_LIVE_OUTPUT` | Enable live streaming | `--live` flag | | `AI_QUIET` | Suppress narration | `--quiet` flag | | `AI_SESSION_ID` | Unique session identifier | Generated per session | ### User Configuration Variables (Set in secrets.sh) | Variable | Purpose | Example | | ------------------------------------ | ------------------------- | ----------------------------------- | | `ANTHROPIC_API_KEY` | Anthropic API key | `sk-ant-...` | | `AWS_PROFILE` | AWS credentials profile | `my-profile` | | `AWS_REGION` | AWS region | `us-west-2` | | `ANTHROPIC_VERTEX_PROJECT_ID` | GCP project ID | `my-project-123` | | `CLOUD_ML_REGION` | Vertex AI region | `global` | | `VERCEL_AI_GATEWAY_TOKEN` | Vercel gateway token | `vck_...` | | `ANTHROPIC_FOUNDRY_API_KEY` | Azure API key | `your-key` | | `ANTHROPIC_FOUNDRY_RESOURCE` | Azure resource name | `your-resource` | | `CLAUDE_MODEL__` | Model override | `CLAUDE_MODEL_OPUS_AWS="..."` | | `CLAUDE_SMALL_FAST_MODEL_` | Background model override | `CLAUDE_SMALL_FAST_MODEL_AWS="..."` | | `AI_NO_UPDATE_CHECK` | Disable update checking | `1` | ## Troubleshooting Configuration ### Check Current Configuration ```bash theme={null} ai-status ``` Shows: * Active provider * Authentication method * Primary model * Small/fast model * Agent teams status * Update availability ### View Effective Model IDs ```bash theme={null} # In an active session ai --aws --opus # > /status # Shows actual ANTHROPIC_MODEL value ``` ### Reset to System Defaults ```bash theme={null} # Remove user overrides nano ~/.ai-runner/secrets.sh # (delete CLAUDE_MODEL_* exports) # Reset models.sh to system defaults cd ~/path/to/airun cp config/models.sh ~/.ai-runner/models.sh ``` ### Verify Override Hierarchy ```bash theme={null} # Check system default grep CLAUDE_MODEL_OPUS_AWS ~/path/to/airun/config/models.sh # Check user copy grep CLAUDE_MODEL_OPUS_AWS ~/.ai-runner/models.sh # Check user override grep CLAUDE_MODEL_OPUS_AWS ~/.ai-runner/secrets.sh # Highest non-empty value wins ``` ## Related Documentation * [Provider Setup](/providers/overview) — Authentication and credentials * [Agent Teams](/advanced/agent-teams) — Multi-agent collaboration * [Scripting Guide](/guides/scripting) — Executable markdown and automation # MCP server for AI agents Source: https://docs.airun.me/advanced/mcp-server Connect your AI coding tools to the AIRun documentation via MCP, llms.txt, and markdown content negotiation. This documentation site exposes an MCP server and llms.txt files so AI coding agents can search and read AIRun documentation directly. ## MCP server The docs site runs a [Model Context Protocol](https://modelcontextprotocol.io/) server that gives your AI tools access to a `SearchAndiAIRun` tool. This tool searches across the AIRun knowledge base to find relevant guides, code examples, and implementation details. **Server URL:** `https://docs.airun.me/mcp` ### Claude Code ```bash theme={null} claude mcp add airun-docs --transport streamable-http https://docs.airun.me/mcp ``` ### Claude web and desktop Add this to your MCP server settings: ```json theme={null} { "mcpServers": { "airun-docs": { "url": "https://docs.airun.me/mcp" } } } ``` ### Cursor Add to your `.cursor/mcp.json`: ```json theme={null} { "mcpServers": { "airun-docs": { "url": "https://docs.airun.me/mcp" } } } ``` ### VS Code Add to your VS Code settings (JSON): ```json theme={null} { "mcp": { "servers": { "airun-docs": { "type": "http", "url": "https://docs.airun.me/mcp" } } } } ``` ### Windsurf Add to your Windsurf MCP configuration: ```json theme={null} { "mcpServers": { "airun-docs": { "url": "https://docs.airun.me/mcp" } } } ``` ## llms.txt The site publishes [llms.txt](https://llmstxt.org/) files that list all documentation pages with direct markdown URLs. | File | Contents | | ------------------------------------------------------- | ------------------------------------------------ | | [`/llms.txt`](https://docs.airun.me/llms.txt) | Page titles and descriptions with markdown links | | [`/llms-full.txt`](https://docs.airun.me/llms-full.txt) | Full page content inlined as markdown | Use `/llms.txt` for discovery and navigation. Use `/llms-full.txt` when you need the complete documentation in a single request. ## Markdown content negotiation Any docs page returns clean markdown when requested with the `Accept: text/markdown` header. The markdown response is smaller than HTML and includes YAML frontmatter. ```bash theme={null} curl -H "Accept: text/markdown" https://docs.airun.me/quickstart ``` The response includes headers for automated discovery: * `Link` headers pointing to `/llms.txt` and `/llms-full.txt` * `X-Llms-Txt` header with the llms.txt URL # ai Source: https://docs.airun.me/cli/ai Universal AI prompt interpreter and Claude Code wrapper The `ai` command is the primary entry point for Andi AIRun. It runs AI prompts as scripts, provides executable markdown with shebang support, and enables cross-cloud provider switching. ## Syntax ```bash theme={null} ai [OPTIONS] [file.md] ai update ``` ## Usage Modes ### Interactive Mode Run `ai` with no arguments to start an interactive session: ```bash theme={null} ai # Regular Claude subscription ai --aws --opus --team # AWS Bedrock with Opus + Agent Teams ai --ollama --bypass # Ollama local with bypassPermissions ai --vercel --model openai/gpt-5.2-codex # Vercel AI Gateway ``` Interactive mode launches Claude Code with your selected provider and model configuration. The session is automatically restored to your original settings on exit. ### Script File Mode Execute a markdown file as a prompt: ```bash theme={null} ai task.md # Uses default provider ai --aws --opus script.md # AWS Bedrock with Opus ai --ollama --haiku task.md # Local Ollama with Haiku tier ``` Script files can contain a shebang line for direct execution: ```markdown theme={null} #!/usr/bin/env ai Analyze this codebase and summarize the architecture. ``` ```bash theme={null} chmod +x task.md ./task.md # Executes directly ``` ### Stdin Mode Pipe content directly to `ai`: ```bash theme={null} echo "Explain what a Makefile does" | ai curl https://example.com/prompt.md | ai git log -10 | ai --aws cat data.json | ./analyze.md > results.txt ``` By default, piped content is prepended to file content. Use `--stdin-position append` to place it after. ## Common Options These are the AI Runner-specific options. See individual reference pages for detailed documentation: Switch between Claude subscriptions and cloud providers Select model tiers or specific model IDs Control file access and command execution permissions Configure output format and streaming behavior ## Flag Precedence When the same configuration is specified in multiple places, AI Runner uses this precedence order (highest to lowest): 1. **CLI flags** - `ai --aws --opus file.md` 2. **Shebang flags** - `#!/usr/bin/env -S ai --aws --opus` 3. **Saved defaults** - `ai --aws --opus --set-default` 4. **Auto-detection** - Current Claude subscription CLI flags always override shebang flags, which override saved defaults. ## Real Examples ### Basic Script Execution ```bash theme={null} # Create an executable prompt cat > greet.md << 'EOF' #!/usr/bin/env ai Say hello and tell me a joke. EOF chmod +x greet.md ./greet.md ``` ### Provider Switching ```bash theme={null} # Run with local Ollama (free, no API key needed) ai --ollama task.md # Run with AWS Bedrock using the strongest model ai --aws --opus task.md # Pipe a remote script to a local model curl https://example.com/prompt.md | ai --ollama ``` ### Unix Pipeline Automation ```bash theme={null} # Pipe in data, redirect output cat data.json | ./analyze.md > results.txt # Feed git history to AI git log -10 | ./summarize.md # Chain scripts together ./generate.md | ./review.md > final.txt ``` ### Agent Teams ```bash theme={null} # Start an interactive session with agent teams on AWS ai --aws --opus --team # Use tmux split panes for teammate display ai --team --teammate-mode tmux ``` ### Persistent Defaults ```bash theme={null} # Save AWS + Opus as your default ai --aws --opus --set-default # Now just run 'ai' - uses saved default ai task.md # Clear saved defaults ai --clear-default ``` ## Script Variables Declare variables with defaults in YAML front-matter: ```markdown theme={null} #!/usr/bin/env -S ai --haiku --- vars: topic: "machine learning" style: casual length: short --- Write a {{length}} summary of {{topic}} in a {{style}} tone. ``` Override from CLI: ```bash theme={null} ./summarize.md --topic "AI safety" --style formal ``` ## Other Commands Update AI Runner to the latest version: ```bash theme={null} ai update ``` Pulls the latest version from the configured GitHub repository and re-runs the setup script. Save current provider+model as persistent default: ```bash theme={null} ai --aws --opus --set-default ``` Remove saved defaults: ```bash theme={null} ai --clear-default ``` Resume the most recent conversation: ```bash theme={null} ai --resume ai --aws --resume # Resume with different provider ai --aws --opus --resume # Resume with different model ``` Picks up your previous conversation exactly where you left off. Works across provider switches - useful when you hit rate limits. Enable agent teams (interactive mode only): ```bash theme={null} ai --team ai --aws --opus --team ai --team --teammate-mode tmux ``` Enables Claude Code's agent teams feature. Multiple AI agents collaborate on tasks with one lead coordinator. **Short form:** `--teams` Select the underlying AI tool: ```bash theme={null} ai --tool cc # Claude Code (default) ai --cc # Shorthand for --tool cc ``` Currently only Claude Code is supported. The `--cc` flag is a shortcut for `--tool cc`. Show version information: ```bash theme={null} ai --version ai -v ``` Show help message: ```bash theme={null} ai --help ai -h ``` ## Session Behavior AI Runner uses session-scoped configuration: * On exit, your original Claude settings are automatically restored * Plain `claude` in another terminal is completely unaffected * No global configuration is changed * Each invocation starts fresh (nested scripts don't inherit parent env vars) ## Passthrough Flags Any flag not recognized by AI Runner is forwarded to Claude Code unchanged: ```bash theme={null} ai --verbose task.md # --verbose passed to Claude Code ai --allowedTools 'Bash' 'Read' task.md # --allowedTools passed through ai --chrome --live test-flow.md # --chrome passed through ``` ## Exit Codes `ai` exits with the same code as the underlying tool (Claude Code). A non-zero exit means the tool reported an error. ## Related Commands Show current configuration List active sessions Update to latest version # ai-sessions Source: https://docs.airun.me/cli/ai-sessions List active AI coding sessions The `ai-sessions` command displays information about currently running `ai` sessions, including the provider, model, and session ID. ## Syntax ```bash theme={null} ai-sessions ``` ## What It Shows For each active session: Unique identifier for the session in format: `{tool}-{provider}-{pid}-{timestamp}` Active provider name (AWS Bedrock, Google Vertex AI, Anthropic API, etc.) Authentication method being used (API key, AWS credentials, subscription, etc.) Primary model ID for interactive work Model ID for background operations (usually Haiku) AI tool being used (typically `cc` for Claude Code) Cloud region (for AWS/GCP providers) Project ID (for Google Vertex AI) Whether agent teams are enabled ## Example Output ```bash theme={null} $ ai-sessions === Active AI Sessions === Session 1: ID: cc-aws-12345-1704067200 Provider: AWS Bedrock Auth: AWS credentials (profile: default) Model: claude-opus-4-6-v1:0 Small/Fast Model: claude-haiku-4-5-20251001-v1:0 Region: us-west-2 Tool: cc (Claude Code) Agent Teams: enabled Session 2: ID: cc-ollama-12346-1704067210 Provider: Ollama Auth: None (local) Model: qwen3-coder Tool: cc (Claude Code) Total sessions: 2 ``` ## Use Cases ### Monitor Active Sessions See what AI sessions are running and which resources they're using: ```bash theme={null} ai-sessions ``` ### Debug Multiple Sessions When running multiple `ai` instances, identify which terminal corresponds to which provider: ```bash theme={null} # Terminal 1 ai --aws --opus # Terminal 2 (different shell) ai-sessions # Shows both sessions with PIDs and providers ``` ### Track Resource Usage Identify sessions using expensive models or cloud resources: ```bash theme={null} ai-sessions | grep opus # Find all Opus sessions ai-sessions | grep aws # Find all AWS sessions ``` ### Session Cleanup Before shutting down, verify all sessions have exited: ```bash theme={null} ai-sessions # Should show "No active sessions" ``` ## Session Lifecycle Sessions are: 1. **Created** when you run `ai` with a script or enter interactive mode 2. **Tracked** in `~/.ai-runner/sessions/` 3. **Cleaned up** automatically on exit 4. **Isolated** - each session has its own environment variables ## Session Information Files Session data is stored in: ``` ~/.ai-runner/sessions/{session-id}.info ``` These files are automatically created and deleted. They contain: * Provider name and configuration * Model IDs * Authentication method * Session metadata ## Exit Cleanup When an `ai` session exits: 1. Session info file is deleted from `~/.ai-runner/sessions/` 2. Environment variables are restored to original state 3. Provider cleanup hooks run (if defined) 4. Temporary files are removed ## No Sessions Running ```bash theme={null} $ ai-sessions === Active AI Sessions === No active sessions. ``` ## Multiple Parallel Sessions You can run multiple `ai` sessions in parallel: ```bash theme={null} # Terminal 1: AWS with Opus for complex work ai --aws --opus --team # Terminal 2: Ollama for quick tests ai --ollama --haiku # Terminal 3: Vertex for specific task ai --vertex script.md # Check all active ai-sessions ``` Each session is independent with its own provider and model configuration. ## Related Commands Start a new AI session Show configuration status # ai-status Source: https://docs.airun.me/cli/ai-status Show current configuration and provider status The `ai-status` command displays your current AI Runner configuration, authentication status, available providers, and model settings. ## Syntax ```bash theme={null} ai-status ``` ## What It Shows ### Authentication Status For each configured provider: * **Authentication method** (API key, credentials file, subscription) * **Status** (✓ configured or ✗ not configured) * **Key presence** (shows whether API keys/credentials are set) ### Model Configuration * **Default model IDs** for each tier (Opus, Sonnet, Haiku) * **Small/fast model** used for background operations * **Custom model overrides** in `~/.ai-runner/secrets.sh` ### Current Session If run inside an active `ai` session: * **Active provider** and model * **Authentication method** in use * **Session ID** ## Example Output ```bash theme={null} $ ai-status === AI Runner Configuration === Version: 1.0.0 Config Directory: ~/.ai-runner --- Authentication Status --- Claude Pro Subscription: Status: ✓ Logged in Auth: Subscription AWS Bedrock: Status: ✓ Configured Profile: default Region: us-west-2 Auth: AWS credentials Google Vertex AI: Status: ✓ Configured Project: my-gcp-project Region: global Auth: Application default credentials Anthropic API: Status: ✓ Configured Auth: API key (sk-ant-...abc123) Azure Foundry: Status: ✗ Not configured Note: Set ANTHROPIC_FOUNDRY_API_KEY in secrets.sh Vercel AI Gateway: Status: ✓ Configured Auth: Gateway token (vck_...xyz789) Ollama: Status: ✓ Available URL: http://localhost:11434 Auth: None (local) LM Studio: Status: ✗ Not running URL: http://localhost:1234 Auth: None (local) --- Model Configuration --- Default Models: Opus (high): claude-opus-4-6-v1:0 Sonnet (mid): claude-sonnet-4-6-v1:0 (default) Haiku (low): claude-haiku-4-5-20251001-v1:0 Small/Fast Model: claude-haiku-4-5-20251001-v1:0 --- Saved Defaults --- Provider: aws Model: --opus Command: ai --aws --opus --- Update Status --- Current version: 1.0.0 Latest version: 1.0.1 Update available! Run: ai update ``` ## Use Cases ### Verify Provider Setup After configuring credentials in `~/.ai-runner/secrets.sh`, run `ai-status` to verify: ```bash theme={null} # Edit credentials nano ~/.ai-runner/secrets.sh # Verify configuration ai-status ``` ### Debug Connection Issues When a provider isn't working: ```bash theme={null} ai-status # Shows which credentials are missing ``` ### Check Active Session From within an `ai` session, run `/status` in Claude or `ai-status` in another terminal to see which provider and model are active. ### View Model Defaults See what model each tier flag resolves to: ```bash theme={null} ai-status # Shows opus/sonnet/haiku model IDs per provider ``` ## Configuration Files The command reads from: * `~/.ai-runner/secrets.sh` - API keys and credentials * `~/.ai-runner/models.sh` - Model ID configuration * `~/.ai-runner/defaults.sh` - Saved defaults from `--set-default` * `~/.claude/settings.json` - Claude subscription status ## Provider Status Indicators | Indicator | Meaning | | ---------------- | ---------------------------------- | | ✓ Configured | Provider has required credentials | | ✗ Not configured | Missing credentials or setup | | ✓ Available | Local provider is running | | ✗ Not running | Local provider service not started | | ✓ Logged in | Claude subscription is active | ## Troubleshooting Add the required credentials to `~/.ai-runner/secrets.sh`: ```bash theme={null} nano ~/.ai-runner/secrets.sh ``` Uncomment and fill in the appropriate section for your provider. For Ollama: ```bash theme={null} ollama serve ``` For LM Studio: ```bash theme={null} lms server start --port 1234 ``` Check for overrides in `~/.ai-runner/secrets.sh`: ```bash theme={null} grep CLAUDE_MODEL ~/.ai-runner/secrets.sh ``` Remove or update model overrides as needed. ## Related Commands Run AI prompts with provider switching List active AI sessions # ai update Source: https://docs.airun.me/cli/ai-update Update AI Runner to the latest version The `ai update` command updates your AI Runner installation to the latest version from the configured GitHub repository. ## Syntax ```bash theme={null} ai update ``` ## What Gets Updated When you run `ai update`, the following are updated: Pulls the latest code from the configured GitHub repository (default: `andisearch/airun`) Installs updated scripts to `/usr/local/bin`: * `ai` / `airun` - main command * `ai-sessions` - session listing * `ai-status` - configuration status * Legacy `claude-*` commands for backward compatibility Updates shared libraries in `/usr/local/share/ai-runner/`: * `lib/` - core utilities and loaders * `providers/` - provider implementations * `tools/` - tool integrations Updates configuration files in `~/.ai-runner/`: * `models.sh` - default model IDs (with prompt before overwriting) * `banner.sh` - banner configuration **Never touches** your API keys and credentials: * `~/.ai-runner/secrets.sh` - preserved unchanged * `~/.ai-runner/defaults.sh` - preserved unchanged ## Version Checking AI Runner automatically checks for updates: * **Frequency**: Once every 24 hours (non-blocking, cache-only) * **Where**: Interactive mode startup and `ai-status` command * **Notification**: Shows a notice when a new version is available ```bash theme={null} $ ai ╔═══════════════════════════════════════╗ ║ 🎯 Andi AI Runner 🎯 ║ ╚═══════════════════════════════════════╝ ⚠️ Update available: 1.0.1 (current: 1.0.0) Run: ai update Claude Code + AWS Bedrock mode activated ... ``` ### Disable Update Checks To disable automatic update checking: ```bash theme={null} export AI_NO_UPDATE_CHECK=1 ``` Add to your shell profile (`~/.bashrc`, `~/.zshrc`) to make permanent. ## Manual Update You can also update manually: ```bash theme={null} cd ~/path/to/airun git pull ./setup.sh ``` This is equivalent to running `ai update`. ## What's Preserved The update process **never** modifies: * **API keys and credentials** in `~/.ai-runner/secrets.sh` * **Saved defaults** in `~/.ai-runner/defaults.sh` * **Session data** in `~/.ai-runner/sessions/` * **Claude configuration** in `~/.claude/` ## Model Configuration Updates When model defaults change between versions, you'll be prompted: ```bash theme={null} $ ai update Model configuration has been updated. Changes include updated default model versions. Note: You have model overrides in secrets.sh. Update to latest model defaults? [Y/n]: ``` * Choose **Y** to update to new model defaults * Choose **n** to keep your current model configuration Your model overrides in `secrets.sh` are always preserved. ## Update Source By default, `ai update` pulls from: ``` https://github.com/andisearch/airun ``` If you installed from a fork or custom source, the update command uses your configured git remote. Check your source: ```bash theme={null} cat /usr/local/share/ai-runner/.source-metadata ``` Update source: ```bash theme={null} cd ~/path/to/airun git remote set-url origin https://github.com/yourusername/airun.git git pull ./setup.sh ``` ## Version History View release notes and version history: * [GitHub Releases](https://github.com/andisearch/airun/releases) * [CHANGELOG.md](https://github.com/andisearch/airun/blob/main/CHANGELOG.md) ## Check Current Version ```bash theme={null} ai --version ``` Or: ```bash theme={null} cat /usr/local/share/ai-runner/VERSION ``` ## Rollback to Previous Version If an update causes issues: ```bash theme={null} cd ~/path/to/airun git log --oneline -10 # Find previous version commit git checkout # Rollback to specific version ./setup.sh # Reinstall ``` ## Update Behavior The `ai update` command requires sudo access if `/usr/local/bin` is not writable by your user. You'll be prompted for your password during the update. Active sessions are not affected by updates. You can continue working in open `ai` sessions while updating. ## Troubleshooting Updates The update process needs to write to `/usr/local/bin`. Run with sudo or ensure the directory is writable: ```bash theme={null} sudo ai update ``` Or make the directory writable: ```bash theme={null} sudo chown -R $USER /usr/local/bin /usr/local/share/ai-runner ai update ``` AI Runner needs git to pull updates. Install git: ```bash theme={null} # macOS brew install git # Ubuntu/Debian sudo apt install git ``` Verify you're on the latest version: ```bash theme={null} ai --version ``` Check if git pulled successfully: ```bash theme={null} cd ~/path/to/airun git log -1 ``` Force reinstall: ```bash theme={null} cd ~/path/to/airun git pull --force ./setup.sh ``` ## Related Commands Show current version Check configuration (includes update status) # Model Flags Source: https://docs.airun.me/cli/model-flags Select model tiers or specific model IDs Model flags let you choose which AI model to use. You can select by tier (Opus, Sonnet, Haiku) or specify an exact model ID. ## Tier Flags ### High Tier (Opus) **Highest-tier model** - Most capable, best for complex reasoning ```bash theme={null} ai --opus task.md ai --aws --opus ai --ollama --opus # Not applicable to Ollama ``` **Equivalent:** `--high` **Default model:** `claude-opus-4-6-v1:0` **Use for:** * Complex architectural decisions * Difficult refactoring * Security analysis * High-stakes code generation Alias for `--opus` ```bash theme={null} ai --high task.md ``` ### Mid Tier (Sonnet) **Mid-tier model** - Balanced capability and speed (default) ```bash theme={null} ai --sonnet task.md ai --aws --sonnet ``` **Equivalent:** `--mid` **Default model:** `claude-sonnet-4-6-v1:0` **Use for:** * Most coding tasks * General development * Documentation * Code review **Note:** This is the default tier when no model flag is specified. Alias for `--sonnet` ```bash theme={null} ai --mid task.md ``` ### Low Tier (Haiku) **Lowest-tier model** - Fastest and most cost-effective ```bash theme={null} ai --haiku task.md ai --aws --haiku ai --ollama --haiku # Not applicable to Ollama ``` **Equivalent:** `--low` **Default model:** `claude-haiku-4-5-20251001-v1:0` **Use for:** * Quick tests * Simple tasks * Cost-sensitive workloads * High-volume automation Alias for `--haiku` ```bash theme={null} ai --low task.md ``` ## Custom Model Selection **Specify exact model ID** - Use any model supported by your provider ```bash theme={null} ai --model claude-opus-4-6 ai --aws --model us.anthropic.claude-opus-4-6-v1:0 ai --ollama --model qwen3-coder ai --vercel --model openai/gpt-5.2-codex ``` **Format depends on provider:** * **AWS Bedrock:** `us.anthropic.claude-opus-4-6-v1:0` * **Vertex AI:** `claude-opus-4-6@20250514` * **Anthropic API:** `claude-opus-4-6` * **Ollama:** Model name from `ollama list` * **Vercel:** `provider/model-name` (e.g., `openai/gpt-4`) **Precedence:** `--model` overrides tier flags (`--opus`, `--sonnet`, `--haiku`) ## Model Defaults Per Provider ### Claude Subscription (Pro/Max) ```bash theme={null} ai --pro # Uses your subscription's latest model ``` Claude Pro/Max doesn't support tier selection - it always uses the latest available model from your subscription. ### API Providers (AWS, Vertex, Anthropic, Azure) | Tier | Default Model | | ---------------------------- | -------------------------------- | | Opus (`--opus`, `--high`) | `claude-opus-4-6-v1:0` | | Sonnet (`--sonnet`, `--mid`) | `claude-sonnet-4-6-v1:0` | | Haiku (`--haiku`, `--low`) | `claude-haiku-4-5-20251001-v1:0` | **Default tier:** Sonnet (mid) ```bash theme={null} ai --aws # Uses Sonnet ai --aws --opus # Uses Opus ai --aws --haiku # Uses Haiku ``` ### Local Providers (Ollama, LM Studio) ```bash theme={null} ai --ollama --model qwen3-coder # Specify model name ai --lmstudio --model mlx-qwen-32b # Specify model name ``` Local providers don't have default models - you must specify with `--model` or configure a default in `~/.ai-runner/secrets.sh`. ### Vercel AI Gateway ```bash theme={null} ai --vercel --model openai/gpt-5.2-codex # OpenAI ai --vercel --model anthropic/claude-opus-4-6 # Anthropic ai --vercel --model google/gemini-exp-2506 # Google ``` Vercel supports 100+ models. Use `provider/model-name` format. See [Vercel AI Gateway docs](https://vercel.com/ai-gateway) for available models. ## Configuration ### View Default Models ```bash theme={null} ai-status # Shows default model IDs for each tier ``` ### Override Model Defaults Edit `~/.ai-runner/secrets.sh`: ```bash theme={null} # Override AWS Sonnet model export CLAUDE_MODEL_SONNET_AWS="global.anthropic.claude-sonnet-4-6" # Override small/fast model (for background operations) export CLAUDE_SMALL_FAST_MODEL_AWS="us.anthropic.claude-haiku-4-5-20251001-v1:0" # Override Vertex Opus model export CLAUDE_MODEL_OPUS_VERTEX="claude-opus-4-6@20250514" ``` See `~/.ai-runner/models.sh` for all available override variables. ## Dual Model Configuration Claude Code uses two models: 1. **Primary model** (`ANTHROPIC_MODEL`) - Interactive work, selected by tier flags 2. **Small/fast model** (`ANTHROPIC_SMALL_FAST_MODEL`) - Background operations (defaults to Haiku) When you run: ```bash theme={null} ai --aws --opus ``` * **Primary:** Opus (`claude-opus-4-6-v1:0`) * **Background:** Haiku (`claude-haiku-4-5-20251001-v1:0`) Both models show in `ai-status` output. ## Examples ### Tier Selection ```bash theme={null} # Most capable (Opus) ai --aws --opus complex-refactor.md # Balanced (Sonnet, default) ai --aws task.md ai --aws --sonnet task.md # Explicit # Fastest/cheapest (Haiku) ai --aws --haiku quick-test.md ``` ### Custom Models ```bash theme={null} # Specific AWS Bedrock model ai --aws --model us.anthropic.claude-opus-4-6-v1:0 # Ollama local model ai --ollama --model qwen3-coder # Ollama cloud model (no GPU needed) ai --ollama --model minimax-m2.5:cloud # Vercel with OpenAI ai --vercel --model openai/gpt-5.2-codex # Vercel with xAI Grok ai --vercel --model xai/grok-2 ``` ### Shebang Scripts ```markdown theme={null} #!/usr/bin/env -S ai --aws --opus Complex task requiring the most capable model. ``` ```markdown theme={null} #!/usr/bin/env -S ai --ollama --model qwen3-coder Local execution with specific model. ``` ### Resume with Different Model ```bash theme={null} # Start with Sonnet ai --aws --sonnet # Resume with Opus for complex reasoning ai --aws --opus --resume # Resume with Haiku for speed ai --aws --haiku --resume ``` ### Cost Optimization ```bash theme={null} # Use Haiku for bulk operations for file in *.md; do ai --aws --haiku --skip "$file" >> results.txt done # Use Opus only for critical review ai --aws --opus --skip final-review.md ``` ## Model Recommendations | Task Type | Recommended Tier | Reason | | -------------------- | ---------------- | ------------------------ | | Complex refactoring | Opus | Needs deep understanding | | Architectural design | Opus | High-stakes decisions | | Security analysis | Opus | Accuracy critical | | General coding | Sonnet | Balanced performance | | Documentation | Sonnet | Good quality/speed ratio | | Code review | Sonnet | Sufficient capability | | Quick tests | Haiku | Speed matters | | Bulk automation | Haiku | Cost-effective | | Simple tasks | Haiku | Overhead not needed | ## Troubleshooting Model IDs are provider-specific. Check your provider's available models: ```bash theme={null} # AWS Bedrock aws bedrock list-foundation-models --region us-west-2 # Ollama ollama list # Vertex AI gcloud ai models list --region=us-central1 ``` See provider documentation for correct model ID format. Check for overrides in `~/.ai-runner/secrets.sh`: ```bash theme={null} grep CLAUDE_MODEL ~/.ai-runner/secrets.sh ``` Verify active model in session: ```bash theme={null} ai-status ``` Local providers (Ollama, LM Studio) don't have tier flags. Use `--model` instead: ```bash theme={null} ai --ollama --model qwen3-coder ``` ## Related Pages Switch between cloud providers Available models per provider # Output Flags Source: https://docs.airun.me/cli/output-flags Control output format, streaming, and input positioning Output flags control how AI Runner displays results, handles streaming, and processes piped input. ## Streaming Flags **Stream output in real-time** - Display AI responses as they're generated ```bash theme={null} ai --live task.md ai --aws --opus --live script.md ai --live --skip automation.md ``` **What it does:** * Enables real-time streaming output * Shows AI response as it's being generated (word by word) * Status messages go to stderr, clean output to stdout * Automatically adds `--output-format stream-json --verbose` **Requirements:** * `jq` must be installed: `brew install jq` **Use for:** * Long-running scripts where you want progress * Scripts that generate reports (output to file, narration to console) * Debugging and monitoring **Example:** ```bash theme={null} # Stream to console, clean output to file ai --live report.md > output.txt ``` **Shebang:** ```markdown theme={null} #!/usr/bin/env -S ai --live --skip Generate a detailed report of the codebase. Print progress updates as you work. ``` **Suppress status messages** - Clean output only (perfect for CI/CD) ```bash theme={null} ai --quiet task.md ai -q script.md ai --live --quiet report.md > output.txt ``` **Short form:** `-q` **What it does:** * Disables `--live` status narration * Suppresses "Using: ..." and "Model: ..." messages * Only shows AI response (clean stdout) * Perfect for piping and file redirection **Use for:** * CI/CD pipelines * Script output that feeds into other tools * File generation without noise **Examples:** ```bash theme={null} # Clean output to file ai --quiet generate.md > output.txt # Pipe to another command ai -q analyze.md | jq '.results' # CI/CD pipeline ai --skip --quiet test-runner.md | tee results.txt ``` ## Input Positioning **Control where piped content goes** - Prepend or append stdin to file content ```bash theme={null} cat data.json | ai task.md --stdin-position prepend cat data.json | ai task.md --stdin-position append ``` **Values:** * `prepend` (default) - Piped content comes before file content * `append` - Piped content comes after file content **Default behavior (prepend):** ```bash theme={null} cat data.json | ai analyze.md # AI sees: # The following input was provided via stdin: # --- # {json data} # --- # # {content of analyze.md} ``` **Append behavior:** ```bash theme={null} cat data.json | ai analyze.md --stdin-position append # AI sees: # {content of analyze.md} # # --- # The following input was provided via stdin: # --- # {json data} ``` **Use prepend for:** * Data-first workflows ("here's the data, now analyze it") * Piping logs/metrics to analysis scripts **Use append for:** * Context-first workflows ("here's the task, here's the data") * Scripts where instructions come first ## Output Format **Claude Code native:** Control output format ```bash theme={null} ai --output-format text task.md ai --output-format json task.md ai --output-format stream-json task.md ``` **Values:** * `text` (default) - Plain text output * `json` - Complete JSON response at end * `stream-json` - Streaming JSON (used by `--live`) **Note:** `--live` automatically sets `stream-json` **Examples:** ```bash theme={null} # Get JSON output ai --output-format json query.md | jq '.response' # Explicit streaming (--live is easier) ai --output-format stream-json --verbose task.md ``` **Claude Code native:** Show detailed execution information ```bash theme={null} ai --verbose task.md ai --aws --verbose debug.md ``` **What it does:** * Shows detailed internal operations * Displays API requests/responses * Useful for debugging issues **Automatically enabled by:** * `--live` flag * `--output-format stream-json` ## Examples ### Real-Time Streaming ```bash theme={null} # Stream output to console ai --live task.md # Stream with file output (status to console, content to file) ai --live report.md > output.txt # Stream with clean stdout (no status) ai --live --quiet script.md > clean-output.txt ``` **Shebang for streaming:** ```markdown theme={null} #!/usr/bin/env -S ai --live --skip Generate a comprehensive report. Print updates as you progress through each section. ``` ### CI/CD Clean Output ```bash theme={null} # Suppress all status messages ai --quiet generate-config.md > config.json ai -q build-report.md | tee report.txt # Pipeline usage ai --skip --quiet test-runner.md | jq '.results.failed' ``` **GitHub Actions:** ```yaml theme={null} steps: - name: Generate docs run: | ai --skip --quiet generate-docs.md > docs/api.md ``` ### Unix Pipelines ```bash theme={null} # Pipe data in, prepend (default) cat data.json | ai analyze.md # Pipe data in, append cat metrics.log | ai summarize.md --stdin-position append # Chain scripts cat input.txt | ./process.md | ./format.md > final.txt # Git history analysis git log --oneline -20 | ai --live summarize-changes.md ``` ### Debugging ```bash theme={null} # Verbose output for debugging ai --verbose --aws debug-connection.md # Live streaming with full visibility ai --live --verbose trace-execution.md ``` ### Report Generation ```markdown theme={null} #!/usr/bin/env -S ai --live Generate a detailed security audit report. For each file you analyze, print: - "Analyzing: {filename}" - Brief summary of findings At the end, print the full report in markdown format. ``` ```bash theme={null} chmod +x audit.md ./audit.md > audit-report.md # Console shows progress, file gets clean markdown ``` ### Dual Output Streams ```bash theme={null} # Live narration goes to stderr (console) # Clean output goes to stdout (file) ai --live report.md > clean-report.txt # Redirect both separately ai --live script.md > output.txt 2> progress.log # Keep narration, discard output ai --live task.md > /dev/null ``` ## Live Streaming Details When you use `--live`: 1. **Status messages** → stderr (your console) 2. **Clean output** → stdout (files, pipes) 3. **Real-time display** → word-by-word as generated 4. **Requires `jq`** → install with `brew install jq` **Example output:** ```bash theme={null} $ ai --live task.md > output.txt Using: Claude Code + AWS Bedrock Model: claude-opus-4-6-v1:0 [Streaming] Analyzing codebase structure... Found 47 source files... Generating architecture diagram... Writing summary... Complete! $ cat output.txt # Codebase Architecture [clean markdown output only] ``` ## Combining Flags ```bash theme={null} # Streaming + permissions + provider ai --aws --opus --live --skip report.md > output.txt # Quiet + permissions + CI/CD ai --skip --quiet generate.md | jq '.config' # Live + quiet (disables live status, keeps streaming) ai --live --quiet task.md # Equivalent to just streaming output # Verbose + live (double verbose, for debugging) ai --live --verbose debug.md ``` ## Stream Processing ### Extract JSON Fields ```bash theme={null} ai --output-format json query.md | jq '.response.text' ``` ### Parse Streaming Output ```bash theme={null} ai --live script.md 2>&1 | grep "^\[" | tee status.log ``` ### Split Streams ```bash theme={null} # Output to file, status to console ai --live task.md > output.txt # Both to separate files ai --live task.md > output.txt 2> status.log # Status only ai --live task.md > /dev/null ``` ## Troubleshooting Install jq for JSON streaming: ```bash theme={null} # macOS brew install jq # Ubuntu/Debian sudo apt install jq # Verify jq --version ``` Status messages go to stdout by default. Use `--quiet` or redirect stderr: ```bash theme={null} # Suppress status ai --quiet task.md > output.txt # Or redirect streams separately ai task.md > output.txt 2> status.log ``` Make sure you're using the AI Runner wrapper, not calling Claude Code directly: ```bash theme={null} # ✅ Correct ai --live task.md # ❌ Won't stream properly claude -p "$(cat task.md)" --output-format stream-json ``` Use `--stdin-position` to control placement: ```bash theme={null} # Context first, then data cat data.json | ai task.md --stdin-position append ``` ## Related Pages Control file access and execution Full automation guide with examples # Permission Flags Source: https://docs.airun.me/cli/permission-flags Control file access and command execution permissions Permission flags control what the AI can do with your system - reading files, writing changes, running commands, and more. These are critical for secure automation. **Security Notice:** Permission shortcuts like `--skip` and `--bypass` give the AI full system access. Only use them with trusted scripts in trusted directories. For production automation, use granular controls like `--allowedTools`. ## Permission Shortcuts These are AI Runner-specific shortcuts that expand to Claude Code's native permission flags. **Skip all permission prompts** - Shortcut for `--dangerously-skip-permissions` ```bash theme={null} ai --skip task.md ai --aws --opus --skip script.md ``` **What it does:** * Disables all permission prompts * AI can read, write, execute without asking * Fastest for automation and CI/CD **Use for:** * Trusted scripts in trusted directories * CI/CD pipelines * Development automation **Warning:** Gives AI full system access. Only run trusted code. **Shebang example:** ```markdown theme={null} #!/usr/bin/env -S ai --skip Run ./test/automation/run_tests.sh and report results. ``` **Bypass permission UI but show actions** - Shortcut for `--permission-mode bypassPermissions` ```bash theme={null} ai --bypass task.md ai --ollama --bypass script.md ``` **What it does:** * Skips permission prompts * Shows what actions are being taken * AI can proceed without waiting for approval **Use for:** * Scripts where you want visibility * Semi-automated workflows * Monitoring what AI does **Shebang example:** ```markdown theme={null} #!/usr/bin/env -S ai --bypass Update documentation files with latest API changes. ``` ## Native Permission Flags These are Claude Code's native flags, passed through by AI Runner. **Claude Code native:** Skip all permission prompts (same as `--skip`) ```bash theme={null} ai --dangerously-skip-permissions task.md ``` Most users should use `--skip` instead for brevity. **Claude Code native:** Set permission behavior mode ```bash theme={null} ai --permission-mode bypassPermissions task.md ai --permission-mode requirePermissions task.md ``` **Values:** * `bypassPermissions` - Same as `--bypass` (skip prompts, show actions) * `requirePermissions` - Default (prompt for each action) * `allowedTools` - Restrict to specific tools (use with `--allowedTools`) **Examples:** ```bash theme={null} # Bypass permissions ai --permission-mode bypassPermissions task.md # Require all permissions (default) ai --permission-mode requirePermissions task.md # Restrict to allowed tools only ai --permission-mode allowedTools --allowedTools 'Read' 'Bash(npm test)' task.md ``` **Claude Code native:** Restrict AI to specific tools and commands ```bash theme={null} ai --allowedTools 'Read' 'Bash' task.md ai --allowedTools 'Bash(npm test)' 'Write(docs/*.md)' script.md ``` **Syntax:** * `'ToolName'` - Allow entire tool (e.g., `'Read'`, `'Bash'`) * `'ToolName(pattern)'` - Allow tool with specific pattern * Multiple tools space-separated **Common tools:** * `Read` - Read files * `Write` - Create/modify files * `Bash` - Run shell commands * `Edit` - Edit existing files * `Grep` - Search file contents * `Glob` - Search file paths **Pattern examples:** ```bash theme={null} # Allow specific commands ai --allowedTools 'Bash(npm test)' 'Bash(git status)' # Allow file operations in specific directory ai --allowedTools 'Read' 'Write(docs/*.md)' # Allow read-only operations ai --allowedTools 'Read' 'Grep' 'Glob' # Allow test execution only ai --allowedTools 'Bash(npm test)' 'Bash(pytest)' 'Read' ``` **Shebang example:** ```markdown theme={null} #!/usr/bin/env -S ai --allowedTools 'Bash(npm test)' 'Read' Run the test suite and report results. Do not modify any files. ``` ## Precedence Rules When multiple permission flags are specified: 1. **Explicit `--permission-mode`** or **`--dangerously-skip-permissions`** takes precedence 2. **Shortcuts** (`--skip`, `--bypass`) are ignored if explicit flags are present 3. **CLI flags** override **shebang flags** 4. **Shebang flags** override **defaults** **Example:** ```bash theme={null} # Script has: #!/usr/bin/env -S ai --skip # But you run: ai --permission-mode requirePermissions script.md # Result: Permission prompts are required (CLI overrides shebang) ``` **Warning message:** ``` ⚠️ --skip ignored: explicit --permission-mode takes precedence ``` ## Permission Modes Compared | Mode | Prompts | Shows Actions | Speed | Safety | | ---------------- | ------- | ------------- | ------- | ------------ | | Default | Yes | Yes | Slowest | Safest | | `--bypass` | No | Yes | Fast | Medium | | `--skip` | No | No | Fastest | Least safe | | `--allowedTools` | No | Yes | Fast | Configurable | ## Examples ### Script Automation (Trusted) ```markdown theme={null} #!/usr/bin/env -S ai --skip Run ./build.sh and commit the results. ``` ```bash theme={null} chmod +x build-and-commit.md ./build-and-commit.md ``` ### Granular Control (Production) ```markdown theme={null} #!/usr/bin/env -S ai --allowedTools 'Bash(npm test)' 'Read' Run the test suite and analyze results. Do not modify files. ``` ```bash theme={null} ./run-tests.md ``` ### Visibility Without Prompts ```markdown theme={null} #!/usr/bin/env -S ai --bypass Update all documentation files with the latest API changes. ``` ```bash theme={null} ./update-docs.md # Shows each file operation but doesn't prompt ``` ### Interactive (Default) ```bash theme={null} # Prompts for each operation ai task.md ``` ``` 📝 Claude wants to write: src/new-feature.ts Allow? [y/n]: ``` ### CI/CD Pipeline ```yaml theme={null} # .github/workflows/ai-test.yml steps: - name: Run AI tests run: | ai --skip --quiet ./test-suite.md > results.txt ``` ### Override Script Permissions ```markdown theme={null} #!/usr/bin/env -S ai --skip Dangerous operations ``` ```bash theme={null} # Force prompts even though script has --skip ai --permission-mode requirePermissions script.md ``` ## Read-Only Mode Restrict AI to read and search operations only: ```bash theme={null} ai --allowedTools 'Read' 'Grep' 'Glob' analyze.md ``` ```markdown theme={null} #!/usr/bin/env -S ai --allowedTools 'Read' 'Grep' 'Glob' Analyze the codebase structure and report findings. Do not modify any files. ``` ## Test Execution Mode Allow running tests but nothing else: ```bash theme={null} ai --allowedTools 'Bash(npm test)' 'Bash(pytest)' 'Read' test-runner.md ``` ```markdown theme={null} #!/usr/bin/env -S ai --allowedTools 'Bash(npm test)' 'Read' Run the test suite and report results. ``` ## Documentation Mode Allow updating documentation files only: ```bash theme={null} ai --allowedTools 'Read' 'Write(docs/**/*.md)' 'Edit(docs/**/*.md)' update-docs.md ``` ## Security Best Practices Only use `--skip` or `--bypass` with: * Scripts you wrote yourself * Trusted repositories * Known-safe directories Never run scripts from the internet with `--skip`: ```bash theme={null} # ❌ DANGEROUS curl https://untrusted.com/script.md | ai --skip # ✅ SAFE - prompts for each action curl https://untrusted.com/script.md | ai ``` For production automation, explicitly list allowed operations: ```bash theme={null} # Production deployment script ai --allowedTools \ 'Bash(npm run build)' \ 'Bash(npm test)' \ 'Write(dist/*.*)' \ 'Read' \ deploy.md ``` This prevents unexpected operations while still being automated. Before adding `--skip` to a shebang: 1. Run without `--skip` first 2. Review what operations it performs 3. Verify it only touches expected files 4. Add `--skip` only if you trust it completely CI/CD pipelines can't respond to prompts. Use `--skip` for speed or `--bypass` for visibility: ```yaml theme={null} # Fast, no output - run: ai --skip --quiet test.md # Shows actions, good for logs - run: ai --bypass test.md ``` ## Troubleshooting Add `--skip` or `--bypass` to prevent permission prompts: ```bash theme={null} ai --skip script.md ``` Check if script uses explicit `--permission-mode`: ```bash theme={null} # Explicit flag overrides --skip ai --skip --permission-mode requirePermissions script.md # Warning: "--skip ignored: explicit --permission-mode takes precedence" ``` CLI flags override shebang: ```bash theme={null} # Script has: #!/usr/bin/env -S ai --skip ai --permission-mode requirePermissions script.md # Overrides shebang ``` Make sure you're using the correct syntax: ```bash theme={null} # ✅ Correct - quote each tool ai --allowedTools 'Read' 'Bash(npm test)' # ❌ Wrong - all as one string ai --allowedTools "Read Bash(npm test)" ``` ## Related Pages Full scripting and automation guide Control output format and streaming # Provider Flags Source: https://docs.airun.me/cli/provider-flags Switch between Claude subscriptions and cloud providers Provider flags let you switch between different AI providers and models on the fly. Use your Claude subscription, cloud platforms, or local models without changing configuration files. ## Available Providers ### Local Providers (Free) **Ollama** - Run models locally or on Ollama's cloud ```bash theme={null} ai --ollama ai --ollama task.md ai --ollama --model qwen3-coder ai --ollama --model minimax-m2.5:cloud # Cloud model, no GPU needed ``` **Short form:** `--ol` **Setup:** ```bash theme={null} brew install ollama # macOS ollama pull qwen3-coder # Pull a model ollama serve # Start server ``` **Requirements:** * Ollama installed and running at `http://localhost:11434` * 24GB+ VRAM for local coding models (cloud models work on any hardware) See [Local Providers](/providers/local) for details. **LM Studio** - Local models with MLX support (fast on Apple Silicon) ```bash theme={null} ai --lmstudio ai --lm task.md ai --lm --model mlx-community/Qwen2.5-Coder-32B-Instruct-4bit ``` **Short form:** `--lm` **Setup:** 1. Download LM Studio from [lmstudio.ai](https://lmstudio.ai) 2. Load a model in the UI 3. Start server: `lms server start --port 1234` **Requirements:** * LM Studio running at `http://localhost:1234` * 24GB+ unified memory for coding models See [Local Providers](/providers/local) for details. ### Cloud Providers **AWS Bedrock** - Claude models on Amazon Web Services ```bash theme={null} ai --aws ai --aws --opus task.md ai --aws --haiku --resume ``` **Setup in `~/.ai-runner/secrets.sh`:** ```bash theme={null} export AWS_PROFILE="your-profile-name" export AWS_REGION="us-west-2" ``` **Authentication:** * AWS credentials file (`~/.aws/credentials`) * Or IAM role (for EC2/ECS) See [Cloud Providers](/providers/cloud) for details. **Google Vertex AI** - Claude models on Google Cloud Platform ```bash theme={null} ai --vertex ai --vertex task.md ai --vertex --sonnet --resume ``` **Setup in `~/.ai-runner/secrets.sh`:** ```bash theme={null} export ANTHROPIC_VERTEX_PROJECT_ID="your-gcp-project-id" export CLOUD_ML_REGION="global" ``` **Authentication:** * Application default credentials (`gcloud auth application-default login`) * Or service account key file See [Cloud Providers](/providers/cloud) for details. **Anthropic API** - Direct access to Anthropic's API ```bash theme={null} ai --apikey ai --apikey --opus task.md ``` **Setup in `~/.ai-runner/secrets.sh`:** ```bash theme={null} export ANTHROPIC_API_KEY="sk-ant-..." ``` **Authentication:** * API key from [console.anthropic.com](https://console.anthropic.com) See [Cloud Providers](/providers/cloud) for details. **Microsoft Azure** - Claude models on Azure Foundry ```bash theme={null} ai --azure ai --azure task.md ``` **Setup in `~/.ai-runner/secrets.sh`:** ```bash theme={null} export ANTHROPIC_FOUNDRY_API_KEY="your-azure-api-key" export ANTHROPIC_FOUNDRY_RESOURCE="your-resource-name" ``` **Authentication:** * Azure Foundry API key See [Cloud Providers](/providers/cloud) for details. **Vercel AI Gateway** - Access 100+ models (OpenAI, xAI, Google, Meta, and more) ```bash theme={null} ai --vercel ai --vercel --model openai/gpt-5.2-codex ai --vercel --model anthropic/claude-opus-4-6 ai --vercel --model google/gemini-exp-2506 ``` **Setup in `~/.ai-runner/secrets.sh`:** ```bash theme={null} export VERCEL_AI_GATEWAY_TOKEN="vck_..." ``` **Authentication:** * Vercel AI Gateway token from [vercel.com/ai-gateway](https://vercel.com/ai-gateway) **Supported models:** * OpenAI (GPT-4, GPT-5, etc.) * xAI (Grok models) * Google (Gemini models) * Meta (Llama models) * Anthropic (Claude models) * And many more See [Cloud Providers](/providers/cloud) for details. **Claude Pro/Max** - Your regular Claude subscription ```bash theme={null} ai --pro ai --pro --resume ``` **Authentication:** * Claude subscription (log in with `claude`) **Note:** This is the default if you're logged in and don't specify another provider. ## Provider Precedence When no provider is specified, AI Runner auto-detects in this order: 1. **Saved default** from `--set-default` 2. **Claude subscription** (if logged in) 3. **Error** (no provider available) CLI flags always override saved defaults. ## Examples ### Basic Usage ```bash theme={null} # Use default provider (Claude subscription) ai task.md # Override to use AWS Bedrock ai --aws task.md # Use local Ollama (free) ai --ollama task.md ``` ### Combining Providers and Models ```bash theme={null} # AWS with Opus ai --aws --opus task.md # Ollama with specific model ai --ollama --model qwen3-coder task.md # Vercel with OpenAI ai --vercel --model openai/gpt-5.2-codex task.md ``` ### Interactive Sessions ```bash theme={null} # Start session with AWS ai --aws # Start with Ollama and bypass permissions ai --ollama --bypass # Start with Vertex and agent teams ai --vertex --team ``` ### Resume Conversations ```bash theme={null} # Hit rate limit on Pro ai --pro # "Rate limit exceeded" # Switch to AWS and continue ai --aws --resume # Or switch to free Ollama ai --ollama --resume ``` ### Shebang Scripts ```markdown theme={null} #!/usr/bin/env -S ai --aws --opus Analyze this codebase with AWS Bedrock. ``` ```markdown theme={null} #!/usr/bin/env -S ai --ollama --haiku Quick analysis with local Ollama. ``` ### Set Default Provider ```bash theme={null} # Save AWS as default ai --aws --set-default # Now 'ai' uses AWS by default ai task.md # Override still works ai --ollama task.md # Clear default ai --clear-default ``` ## Provider Status Check which providers are configured: ```bash theme={null} ai-status ``` See [ai-status reference](/cli/ai-status) for details. ## Multiple Providers Workflow Switch between providers based on your needs: ```bash theme={null} # Quick tests: use free Ollama ai --ollama --haiku quick-test.md # Complex tasks: use AWS with Opus ai --aws --opus complex-task.md # Cost-sensitive: use Haiku on any provider ai --apikey --haiku analyze.md # Rate-limited: fall back to different provider ai --aws --resume # Continue after hitting Pro rate limit ``` ## Related Pages Select model tiers and specific model IDs Detailed setup for each provider # Executable Markdown Source: https://docs.airun.me/concepts/executable-markdown Turn markdown files into AI-powered scripts with shebang support Andi AIRun makes markdown files executable using Unix shebang syntax. Add a shebang line to any markdown file, make it executable, and run it directly as a command. ## How Shebang Scripts Work A shebang (`#!`) at the start of a file tells the operating system which interpreter to use. AIRun uses `#!/usr/bin/env ai` to run markdown files as AI prompts: ```markdown theme={null} #!/usr/bin/env ai Analyze this codebase and summarize the architecture. ``` **Make it executable and run:** ```bash theme={null} chmod +x task.md ./task.md ``` The AI reads the prompt from the file and executes it in your current directory, just like running `ai task.md`. ## The `-S` Flag Requirement Standard `env` only accepts **one argument**. If you want to pass flags to `ai` in your shebang, you must use `env -S` to split the string into multiple arguments: ```markdown Works - no flags theme={null} #!/usr/bin/env ai Summarize this project. ``` ```markdown Works - with -S flag theme={null} #!/usr/bin/env -S ai --aws --opus Analyze this code using AWS Bedrock with Opus. ``` ```markdown FAILS - missing -S theme={null} #!/usr/bin/env ai --aws --opus # Error: env treats "ai --aws --opus" as a single command ``` Always use `#!/usr/bin/env -S ai` when your shebang includes flags like `--aws`, `--skip`, or `--live`. ## Shebang Examples from the Repository ### Basic Hello World From `examples/hello.md`: ```markdown theme={null} #!/usr/bin/env -S ai --haiku Say hello and briefly explain what you can do. ``` The `--haiku` flag selects a fast, cost-effective model for simple tasks. ### Code Analysis From `examples/analyze-code.md`: ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip Summarize the architecture of this codebase. List the main entry points, key modules, and how data flows through the system. ``` * `--sonnet`: Balanced model for code analysis * `--skip`: Shortcut for `--dangerously-skip-permissions` — allows the AI to read files without prompting ### Live Streaming Report From `examples/live-report.md`: ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip --live Explore this repository and write a short summary of what it does, its key features, and how to get started. Print your findings as you go. Finally, generate a concise report in markdown format. ``` The `--live` flag streams output in real-time as the AI works, showing progress incrementally. ### Test Automation From `examples/run-tests.md`: ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip Run the test suite for this project. Report which tests passed and which failed. If any tests fail, explain the root cause. ``` ### Stdin Processing From `examples/analyze-stdin.md`: ```markdown theme={null} #!/usr/bin/env -S ai --haiku Analyze the data provided on stdin. Summarize the key points, highlight anything unusual, and suggest next steps. ``` Run with piped input: ```bash theme={null} cat data.json | ./analyze-stdin.md ``` ### Script with Variables From `examples/summarize-topic.md`: ```markdown theme={null} #!/usr/bin/env -S ai --haiku --- vars: topic: "machine learning" style: casual length: short --- Write a {{length}} summary of {{topic}} in a {{style}} tone. ``` Override variables from the command line: ```bash theme={null} ./summarize-topic.md --topic "AI safety" --style formal --length "detailed" ``` ## Permission Modes for Automation **Read-only scripts** (default) can analyze code but won't modify anything: ```markdown theme={null} #!/usr/bin/env ai Analyze the test coverage in this codebase. ``` **Automation scripts** that need to write files or run commands require permission flags: ```markdown --skip (common) theme={null} #!/usr/bin/env -S ai --skip Run the test suite and fix any failing tests. ``` ```markdown --bypass (composable) theme={null} #!/usr/bin/env -S ai --bypass Run the linter and auto-fix all issues. ``` ```markdown --allowedTools (granular) theme={null} #!/usr/bin/env -S ai --allowedTools 'Bash(npm test)' 'Read' Run tests and report results. Do not modify files. ``` `--skip` and `--bypass` give the AI full system access. Only run trusted scripts in trusted directories. For granular control, use `--allowedTools` to specify exactly which operations are allowed. ## Flag Precedence When you run a script, flags are resolved in this order (highest priority first): | Priority | Source | Example | | --------------- | -------------- | ------------------------------------- | | **1 - Highest** | CLI flags | `ai --aws --opus script.md` | | **2** | Shebang flags | `#!/usr/bin/env -S ai --ollama --low` | | **3** | Saved defaults | `ai --aws --opus --set-default` | | **4 - Lowest** | Auto-detection | Current Claude subscription | **Example precedence in action:** Given a script with this shebang: ```markdown theme={null} #!/usr/bin/env -S ai --ollama --low Analyze this code. ``` ```bash theme={null} ./script.md # Uses Ollama (shebang) ai script.md # Uses Ollama (shebang) ai --aws script.md # Uses AWS (CLI overrides shebang) ``` If you've also run `ai --vertex --set-default`: ```bash theme={null} ai script.md # Still uses Ollama (shebang beats saved default) ai --resume # Uses Vertex (no script, so default applies) ``` CLI flags always override shebang flags, and shebang flags always override saved defaults. This lets you keep scripts with sensible defaults while overriding them when needed. ## Passthrough Flags AIRun handles its own flags (`--aws`, `--opus`, `--live`, `--skip`, etc.) and passes unrecognized flags directly to Claude Code: ```markdown theme={null} #!/usr/bin/env -S ai --skip --chrome --max-turns 10 Navigate to the app and verify the login flow works. ``` * `--skip`: AIRun flag (permission mode) * `--chrome`: Claude Code flag (browser automation) * `--max-turns 10`: Claude Code flag (limit iterations) ## Running Scripts There are three ways to run executable markdown: ```bash theme={null} chmod +x script.md ./script.md ``` Uses shebang flags exactly as written. ```bash theme={null} ai script.md ai --aws script.md # Override provider ``` CLI flags override shebang flags. ```bash theme={null} cat script.md | ai curl -fsSL https://example.com/script.md | ai ``` Shebang flags are still honored even when piped. ## Combining with Other Features Shebang scripts work seamlessly with other AIRun features: **Provider switching:** ```markdown theme={null} #!/usr/bin/env -S ai --aws --opus ``` **Live streaming:** ```markdown theme={null} #!/usr/bin/env -S ai --live --skip ``` **Agent teams:** ```markdown theme={null} #!/usr/bin/env -S ai --team --opus ``` **Custom models:** ```markdown theme={null} #!/usr/bin/env -S ai --ollama --model qwen3-coder ``` Chain scripts together and process data streams Switch between cloud providers and models # Provider Switching Source: https://docs.airun.me/concepts/provider-switching Switch between cloud providers and models to avoid rate limits and optimize costs Andi AIRun extends Claude Code with multi-provider support. Switch between your Claude subscription, AWS Bedrock, Google Vertex AI, Azure, local models, and more — all using the same `ai` command. ## What Are Providers? Providers are different backend services that run AI models. Each provider has its own: * **Authentication**: API keys, credentials, or subscriptions * **Pricing**: Some free (local), some pay-per-token (API), some subscription (Claude Pro) * **Rate limits**: Different limits per provider and tier * **Model selection**: Not all providers have all models * **Geographic regions**: Different data residency and compliance ### Available Providers | Provider | Type | Flag | Notes | | --------------------- | ------------ | ------------ | ------------------------------------- | | **Claude Pro** | Subscription | `--pro` | Default if logged in, has rate limits | | **AWS Bedrock** | Cloud API | `--aws` | Requires AWS credentials | | **Google Vertex AI** | Cloud API | `--vertex` | Requires GCP project | | **Anthropic API** | Cloud API | `--apikey` | Direct API access | | **Azure** | Cloud API | `--azure` | Microsoft Azure Foundry | | **Vercel AI Gateway** | Cloud API | `--vercel` | 100+ models from multiple providers | | **Ollama** | Local/Cloud | `--ollama` | Free local or cloud models | | **LM Studio** | Local | `--lmstudio` | Local models with MLX support | Providers are configured once in `~/.ai-runner/secrets.sh` and switched with simple flags. No need to edit config files or set environment variables. ## Why Switch Providers? There are several reasons to switch providers mid-task: ### 1. Avoiding Rate Limits The most common reason. Claude Pro has rate limits that can block you for hours: ```bash theme={null} # Working with Claude Pro, hit rate limit claude # "Rate limit exceeded. Try again in 4 hours 23 minutes." # Immediately continue with AWS ai --aws --resume ``` You can continue your exact conversation on a different provider without losing context. ### 2. Cost Optimization Different providers have different pricing: ```bash theme={null} # Use cheap Haiku for simple analysis ai --aws --haiku analyze-logs.md # Use expensive Opus for complex reasoning ai --aws --opus review-architecture.md # Use free local model for experimentation ai --ollama --model qwen3-coder ``` ### 3. Local vs Cloud Run models locally for privacy, or in the cloud for power: ```bash theme={null} # Local - free, private, no API calls ai --ollama analyze-sensitive-data.md # Cloud - more powerful, faster ai --aws --opus analyze-complex-system.md ``` ### 4. Geographic Compliance Different providers operate in different regions: ```bash theme={null} # Use GCP for EU data residency ai --vertex task.md # Use Azure for specific compliance requirements ai --azure task.md ``` ### 5. Model Availability Test different models or use alternate AI systems: ```bash theme={null} # Claude via AWS ai --aws --opus task.md # OpenAI via Vercel ai --vercel --model openai/gpt-5.2-codex task.md # xAI via Vercel ai --vercel --model xai/grok-code-fast-1 task.md # Local Ollama ai --ollama --model qwen3-coder task.md ``` ## The --resume Flag for Continuity The `--resume` flag picks up your previous conversation on a different provider: ```bash theme={null} # Start with Claude Pro ai # [work for a while...] # "Rate limit exceeded" # Resume on AWS with same context ai --aws --resume ``` What `--resume` does: * Loads the most recent conversation session * Continues from where you left off * Preserves all context and history * Works across any provider switch **Use cases:** ```bash theme={null} ai # Hit rate limit ai --aws --resume # Continue immediately ``` ```bash theme={null} ai --opus # Start with powerful model ai --haiku --resume # Switch to cheap model for simple tasks ai --opus --resume # Back to powerful for complex work ``` ```bash theme={null} ai --ollama # Try local first ai --aws --opus --resume # Escalate to cloud for hard problem ``` ```bash theme={null} ai --aws --resume # Try AWS implementation ai --vertex --resume # Compare Vertex response ai --azure --resume # Test Azure behavior ``` Use `ai-sessions` to view your active conversation sessions and see which one would be resumed. ## Session-Scoped Behavior All provider switches are **session-scoped** — they only affect the current terminal session: ```bash theme={null} # Terminal 1 ai --aws # [Working with AWS...] # Terminal 2 (unaffected) claude # [Still using regular Claude Pro] ``` When you exit an `ai` session: * Your original Claude Code settings are automatically restored * No global configuration is changed * Other terminals are completely unaffected This non-destructive design means you can safely experiment with providers without breaking your Claude Code installation. ## Setting Default Providers If you frequently use a specific provider, save it as your default: ```bash theme={null} # Set AWS + Opus as default ai --aws --opus --set-default # Now 'ai' with no flags uses AWS + Opus ai ai --resume # Clear saved default ai --clear-default # Back to auto-detection (Claude Pro if logged in) ai ``` Saved defaults are stored in `~/.ai-runner/default.conf`. **Flag precedence** (highest to lowest): | Priority | Source | Example | | ----------------- | --------------- | --------------------------------- | | 1. CLI flags | Explicit flags | `ai --vertex task.md` | | 2. Shebang flags | Script header | `#!/usr/bin/env -S ai --aws` | | 3. Saved defaults | `--set-default` | Set with `ai --aws --set-default` | | 4. Auto-detection | Current login | Claude Pro if logged in | ## Provider Examples ### Switch Between Major Clouds ```bash theme={null} # AWS Bedrock ai --aws ai --aws --opus task.md # Google Vertex AI ai --vertex ai --vertex --sonnet task.md # Microsoft Azure ai --azure ai --azure --haiku task.md ``` ### Use Anthropic API Directly ```bash theme={null} # Direct API (bypasses subscription limits) ai --apikey ai --apikey --opus task.md ``` ### Local Models (Free) ```bash theme={null} # Ollama (local) ai --ollama ai --ollama --model qwen3-coder # Ollama (cloud, no GPU needed) ai --ollama --model minimax-m2.5:cloud ai --ollama --model glm-5:cloud # LM Studio (local, MLX support) ai --lmstudio ai --lm --model openai/gpt-oss-20b ``` ### Alternate Models via Vercel ```bash theme={null} # OpenAI models ai --vercel --model openai/gpt-5.2-codex # xAI models ai --vercel --model xai/grok-code-fast-1 # Google models ai --vercel --model google/gemini-3-pro-preview # Alibaba models ai --vercel --model alibaba/qwen3-coder ``` Vercel AI Gateway gives access to 100+ models from multiple providers through a single API. ## Model Tiers Most providers support three model tiers: | Tier | Flags | Use Case | Example | | -------- | -------------------- | ------------------------------- | ---------- | | **High** | `--opus` / `--high` | Complex reasoning, architecture | Opus 4.6 | | **Mid** | `--sonnet` / `--mid` | Balanced coding tasks | Sonnet 4.6 | | **Low** | `--haiku` / `--low` | Fast, simple tasks | Haiku 4.5 | Combine tiers with providers: ```bash theme={null} ai --aws --opus # AWS Bedrock + Opus ai --vertex --sonnet # Vertex AI + Sonnet ai --azure --haiku # Azure + Haiku ``` Use `--haiku` for cost savings on simple tasks. Use `--opus` for complex architecture decisions or challenging debugging. Use `--sonnet` (default) for everyday coding. ## Provider Configuration Providers are configured in `~/.ai-runner/secrets.sh`: ```bash theme={null} # Edit configuration nano ~/.ai-runner/secrets.sh ``` Add credentials for the providers you want to use: ```bash theme={null} # AWS Bedrock export AWS_PROFILE="your-profile-name" export AWS_REGION="us-west-2" # Google Vertex AI export ANTHROPIC_VERTEX_PROJECT_ID="your-gcp-project-id" export CLOUD_ML_REGION="global" # Anthropic API export ANTHROPIC_API_KEY="sk-ant-..." # Vercel AI Gateway export VERCEL_AI_GATEWAY_TOKEN="vck_..." # Azure export ANTHROPIC_FOUNDRY_API_KEY="your-azure-api-key" export ANTHROPIC_FOUNDRY_RESOURCE="your-resource-name" # Ollama (local) # No configuration needed # LM Studio (local) export LMSTUDIO_HOST="http://localhost:1234" # Optional ``` You only need to configure the providers you plan to use. Configuration is loaded at startup. After editing `secrets.sh`, start a new session or run `source ~/.ai-runner/secrets.sh`. ## Check Current Configuration Use `ai-status` to verify your setup: ```bash theme={null} ai-status ``` **Example output:** ``` Andi AIRun Status ================= Version: 1.5.0 Providers Configured: ✓ Claude Pro (logged in) ✓ AWS Bedrock (profile: default, region: us-west-2) ✓ Anthropic API (key: sk-ant-...ABC123) ✓ Ollama (local, 3 models available) ✗ Vertex AI (not configured) ✗ Azure (not configured) ✗ Vercel (not configured) Default Provider: AWS Bedrock + Opus 4.6 Active Sessions: 2 - Session 1: AWS Bedrock + Sonnet (started 2h ago) - Session 2: Claude Pro (started 15m ago) ``` ## Advanced: Agent Teams with Any Provider Agent teams work with all providers: ```bash theme={null} # Claude Pro with teams ai --team # AWS with teams ai --aws --opus --team # Local Ollama with teams ai --ollama --team ``` Teams coordination uses Claude Code's internal task list and mailbox — it's provider-independent. Token usage scales with team size (5 teammates ≈ 5× tokens). Agent teams only work in interactive mode — not supported in shebang/piped script modes. ## Practical Workflows ### Rate Limit Recovery Workflow ```bash theme={null} # 1. Start working with Claude Pro ai # 2. Hit rate limit mid-task # "Rate limit exceeded. Try again in 4 hours 23 minutes." # 3. Immediately switch to API ai --aws --resume # 4. Continue working # [Complete the task...] # 5. Later, switch back to Pro for free tier ai --pro --resume ``` ### Cost-Optimized Development ```bash theme={null} # Use free local model for exploration ai --ollama # [Prototype and experiment...] # Switch to cloud for production-quality code ai --aws --opus --resume # [Final implementation...] # Use cheap Haiku for documentation ai --aws --haiku --resume # [Generate docs...] ``` ### Multi-Provider Testing ```bash theme={null} # Test a prompt on different providers ai --aws task.md > aws-output.txt ai --vertex task.md > vertex-output.txt ai --ollama task.md > ollama-output.txt # Compare results diff aws-output.txt vertex-output.txt ``` ### Privacy-Conscious Workflow ```bash theme={null} # Sensitive data analysis (local only) ai --ollama analyze-customer-data.md # Public code review (cloud OK) ai --aws review-open-source-pr.md ``` ## View Active Sessions See all your conversation sessions: ```bash theme={null} ai-sessions ``` **Example output:** ``` Active AIRun Sessions: 1. AWS Bedrock + Sonnet 4.6 Started: 2 hours ago Location: ~/projects/backend/ Status: Active 2. Claude Pro + Opus 4.6 Started: 15 minutes ago Location: ~/projects/frontend/ Status: Active 3. Ollama (qwen3-coder) Started: 1 day ago Location: ~/experiments/ Status: Idle ``` The most recent session is used by `--resume`. Detailed configuration for each provider Use provider flags in shebang scripts # Unix Pipes Source: https://docs.airun.me/concepts/unix-pipes Chain AI scripts together with stdin/stdout for automation pipelines Andi AIRun scripts follow Unix philosophy: read from stdin, write to stdout, chain together in pipelines. This enables powerful automation workflows where AI scripts act as composable filters. ## Stdin/Stdout Handling Executable markdown scripts have proper Unix stream semantics: * **Stdin support**: Pipe data directly into scripts * **Clean stdout**: AI responses go to stdout when redirected * **Diagnostic stderr**: Status messages and progress go to stderr * **Chainable**: Connect scripts in pipelines like standard Unix tools ### Basic Piping Pipe data into a script: ```bash theme={null} cat data.json | ./analyze.md git log --oneline -20 | ./summarize-changes.md echo "Explain what a Dockerfile does" | ai ``` The piped content is automatically included in the prompt sent to the AI. ### Output Redirection Redirect AI output to a file: ```bash theme={null} ./analyze.md > results.txt ai task.md > output.md ``` When stdout is redirected, you get **only the AI's response** — no status messages, no prompts. Status information goes to stderr so you can still see progress: ```bash theme={null} $ ./analyze.md > results.txt [AI Runner] Using: Claude Code + Claude Pro [AI Runner] Model: claude-sonnet-4-6 [Processing...] [AI Runner] Done ``` This clean separation between content (stdout) and diagnostics (stderr) makes AIRun scripts perfect for automation and CI/CD pipelines. ## The stdin-position Flag By default, piped input is **prepended** to the prompt (added before the script content). Use `--stdin-position` to control where stdin appears: ```bash Prepend (default) theme={null} cat data.json | ./analyze.md # Effective prompt: [data.json contents] + [analyze.md contents] ``` ```bash Append theme={null} cat data.json | ./analyze.md --stdin-position append # Effective prompt: [analyze.md contents] + [data.json contents] ``` **When to use append:** Some prompts work better with instructions first, data second: ```markdown theme={null} #!/usr/bin/env -S ai --haiku Analyze the following JSON data. Extract the top 5 trends and format as markdown. ``` ```bash theme={null} cat data.json | ./analyze.md --stdin-position append ``` Effective prompt: ``` Analyze the following JSON data. Extract the top 5 trends and format as markdown. [data.json contents] ``` ## Chaining Scripts Together Chain multiple AI scripts in a pipeline: ```bash theme={null} ./generate-report.md | ./format-output.md > final.txt ./parse-logs.md | ./analyze-patterns.md | ./create-dashboard.md ``` Each script: 1. Reads from stdin (previous script's output) 2. Processes with AI 3. Writes result to stdout (next script's input) From the test suite (`test/automation/`): ```bash theme={null} # Three-stage pipeline ./generate-report.md | ./format-output.md | ./analyze.md > result.txt ``` Chained scripts run with process isolation — environment variables are cleared between nested calls, so each script starts fresh. This prevents state leakage and makes pipelines more predictable. ## Real Examples from the Repository ### Analyze Piped Data From `examples/analyze-stdin.md`: ```markdown theme={null} #!/usr/bin/env -S ai --haiku Analyze the data provided on stdin. Summarize the key points, highlight anything unusual, and suggest next steps. ``` **Usage:** ```bash theme={null} cat package.json | ./analyze-stdin.md df -h | ./analyze-stdin.md > disk-report.txt curl -s https://api.example.com/stats | ./analyze-stdin.md ``` ### Generate and Process From `test/automation/generate-report.md` and `format-output.md`: ```bash theme={null} # Generate a report ./generate-report.md > raw-report.txt # Generate and immediately format ./generate-report.md | ./format-output.md > formatted.txt ``` ### Git Workflow Integration ```bash theme={null} # Summarize recent commits git log -10 --oneline | ./summarize-changes.md # Analyze diff before committing git diff | ./review-changes.md # Generate commit message from staged changes git diff --cached | ./suggest-commit-message.md ``` ### Log Analysis ```bash theme={null} # Analyze application logs tail -n 100 app.log | ./analyze-errors.md > error-summary.txt # Monitor and summarize in real-time tail -f access.log | ./detect-anomalies.md ``` ## Live Streaming with Pipes Combine `--live` with pipes to see real-time progress: ```bash theme={null} cat large-dataset.json | ai --live --skip analyze.md ``` **Console output (stderr):** ``` [AI Runner] Using: Claude Code + Claude Pro [AI Runner] Model: claude-sonnet-4-6 I'm analyzing the dataset structure... Found 1,247 records spanning 3 categories... Detecting outliers in the price field... Generating summary statistics... ``` **File output (stdout):** ```bash theme={null} cat data.json | ./analyze.md --live > report.md ``` Narration streams to console (stderr), final report goes to file (stdout). ## Output Redirection with Live Mode When stdout is redirected with `--live`, AIRun intelligently splits the output: ```bash theme={null} ./live-report.md > report.md ``` **What you see on console (stderr):** ``` [AI Runner] Using: Claude Code + Claude Pro [AI Runner] Model: claude-sonnet-4-6 I'll explore the repository structure... Found 15 source files in src/... Analyzing key modules... Here's my report: [AI Runner] Done (70 lines written) ``` **What goes to the file (stdout):** ```markdown theme={null} # Repository Summary ## Overview This project implements... ## Key Features 1. Executable markdown scripts 2. Provider switching ... ``` The split happens automatically: * Intermediate turns (narration) → stderr * Final turn preamble (before first `---` or `#`) → stderr * Final turn content (from first marker onward) → stdout This behavior makes `--live` ideal for long-running scripts where you want to see progress but only capture the final result in a file. ## Shell Script Integration Use AIRun scripts in traditional shell scripts: ```bash theme={null} #!/bin/bash # Batch process log files for file in logs/*.txt; do echo "Processing $file..." cat "$file" | ./analyze-logs.md >> summary.txt echo "---" >> summary.txt done echo "Analysis complete. Summary saved to summary.txt" ``` ## CI/CD Pipeline Integration **GitHub Actions example:** ```yaml theme={null} name: AI Code Review on: [pull_request] jobs: review: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Run AI review run: | git diff origin/main...HEAD | ./review-pr.md > review.txt cat review.txt >> $GITHUB_STEP_SUMMARY ``` **GitLab CI example:** ```yaml theme={null} ai-review: script: - git diff origin/main...HEAD | ./review-changes.md > review.md artifacts: paths: - review.md ``` ## Running Scripts from the Web AIRun supports `installmd.org` style execution: ```bash theme={null} # Run a script directly from a URL curl -fsSL https://example.com/analyze.md | ai # Override provider from shebang curl -fsSL https://example.com/script.md | ai --aws --opus # Pipe data through a remote script cat data.json | curl -fsSL https://example.com/process.md | ai ``` Only pipe trusted remote scripts, especially when using permission flags like `--skip` or `--bypass`. Remote scripts have the same access as local scripts. ## Composable Design Patterns ### Single-Purpose Scripts Follow Unix philosophy — each script does one thing well: ```bash theme={null} # Extract data ./extract-metrics.md < raw-data.json > metrics.json # Transform data ./normalize-metrics.md < metrics.json > normalized.json # Generate report ./create-report.md < normalized.json > report.md ``` Or chain them: ```bash theme={null} cat raw-data.json | ./extract-metrics.md | ./normalize-metrics.md | ./create-report.md > report.md ``` ### The Dispatcher Pattern Use `--cc --skip` to give the AI tool access in a top-level script, then call simple prompt-mode scripts from within: ```markdown theme={null} #!/usr/bin/env -S ai --cc --skip --live Read all test files in test/ directory. For each test file, describe what it tests and verify the assertions are comprehensive. Print findings as you go. ``` The dispatcher has tool access and can: * Read files * Run commands * Chain to other scripts Child scripts should be simple prompt-mode (no `--cc`) to avoid nested tool complexity. See the [Scripting Guide](/guides/scripting) for more details on the dispatcher pattern and composable script design. ## stdin Position Examples ### Instructions + Data (append) ```markdown theme={null} #!/usr/bin/env -S ai --haiku Extract all error messages from the following log data and count occurrences: ``` ```bash theme={null} cat app.log | ./extract-errors.md --stdin-position append ``` ### Data + Question (prepend, default) ```markdown theme={null} #!/usr/bin/env ai What are the top 3 issues in this data? ``` ```bash theme={null} cat issues.json | ./summarize.md # Default prepend: data comes first, then question ``` ## Process Isolation When chaining scripts, AIRun clears inherited environment variables between nested calls: ```bash theme={null} ./script1.md | ./script2.md | ./script3.md ``` Each script: * Gets a fresh environment * No leaked state from previous scripts * Predictable, reproducible behavior This prevents accidental context leakage and makes pipelines more reliable. Learn about shebang support and script structure Complete guide to writing AI automation scripts # CI/CD Integration Source: https://docs.airun.me/examples/ci-cd Run AIRun in GitHub Actions, GitLab CI, and other automation platforms Integrate AIRun into your CI/CD pipelines for automated testing, code analysis, documentation generation, and more. ## Key Concepts for CI/CD ### Permission Modes for Automation CI/CD scripts need to run without interactive prompts. Use these permission modes: | Mode | Flag | When to Use | | -------------------- | ---------------------------------------- | ------------------------------------------------- | | **Skip Permissions** | `--skip` | Full automation (test running, file generation) | | **Bypass Mode** | `--bypass` | Composable automation with permission mode system | | **Allowed Tools** | `--allowedTools 'Read' 'Bash(npm test)'` | Granular control (security-critical pipelines) | `--skip` and `--bypass` give the AI full system access. In CI/CD: * Run inside containers for isolation * Use `--allowedTools` for security-critical pipelines * Never expose secrets in prompts * Review scripts before adding to CI ### Provider Selection CI/CD environments need API-based providers (not Claude Pro subscription): | Provider | Flag | Setup Required | | ----------------- | ---------- | --------------------------- | | **Anthropic API** | `--apikey` | Set `ANTHROPIC_API_KEY` | | **AWS Bedrock** | `--aws` | Configure AWS credentials | | **Google Vertex** | `--vertex` | Set GCP project ID | | **Azure** | `--azure` | Azure API key | | **Vercel AI** | `--vercel` | Vercel gateway token | | **Ollama** | `--ollama` | Ollama server (self-hosted) | **Recommended for CI/CD:** `--apikey` (Anthropic API) for simplicity. Just add `ANTHROPIC_API_KEY` to your CI secrets and use `ai --apikey --skip`. ### Model Selection for Cost | Task | Model | Why | | ---------------------------------- | ---------- | ------------------ | | Lint output parsing, simple checks | `--haiku` | Cheapest, fastest | | Test analysis, code review | `--sonnet` | Balanced (default) | | Complex architecture validation | `--opus` | Most capable | ## GitHub Actions ### Basic Test Analysis ```yaml theme={null} name: AI Test Analysis on: [push, pull_request] jobs: test-analysis: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Node.js uses: actions/setup-node@v3 with: node-version: '20' - name: Install dependencies run: npm install - name: Install AIRun run: | curl -fsSL https://claude.ai/install.sh | bash git clone https://github.com/andisearch/airun.git cd airun && ./setup.sh - name: Run tests with AI analysis run: | ai --apikey --sonnet --skip << 'EOF' > test-report.md Run the test suite (npm test). Report pass/fail counts. If any tests fail, analyze root causes and suggest fixes. EOF env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - name: Upload test report uses: actions/upload-artifact@v3 if: always() with: name: test-analysis path: test-report.md - name: Comment on PR if: github.event_name == 'pull_request' uses: actions/github-script@v6 with: script: | const fs = require('fs'); const report = fs.readFileSync('test-report.md', 'utf8'); github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: `## AI Test Analysis\n\n${report}` }); ``` ### Automated Code Review ```yaml theme={null} name: AI Code Review on: pull_request: types: [opened, synchronize] jobs: review: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: fetch-depth: 0 # Need full history for diff - name: Install AIRun run: | curl -fsSL https://claude.ai/install.sh | bash git clone https://github.com/andisearch/airun.git cd airun && ./setup.sh - name: Run AI code review run: | ai --apikey --opus --skip << 'EOF' > review.md Review the changes in this pull request. Focus on: - Security vulnerabilities (OWASP Top 10) - Performance issues - Code quality and maintainability - Test coverage Be specific with file paths and line numbers. Rate severity: CRITICAL, HIGH, MEDIUM, LOW. EOF env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - name: Post review as PR comment uses: actions/github-script@v6 with: script: | const fs = require('fs'); const review = fs.readFileSync('review.md', 'utf8'); github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: `## 🤖 AI Code Review\n\n${review}` }); ``` ### Documentation Generation ```yaml theme={null} name: Generate Documentation on: push: branches: [main] paths: - 'src/**' - 'lib/**' jobs: docs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Install AIRun run: | curl -fsSL https://claude.ai/install.sh | bash git clone https://github.com/andisearch/airun.git cd airun && ./setup.sh - name: Generate architecture docs run: | ai --apikey --sonnet --skip << 'EOF' > ARCHITECTURE.md Document the codebase architecture: - Main entry points - Key modules and their responsibilities - Data flow through the system - Important design patterns Output in markdown format suitable for a documentation site. EOF env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - name: Generate API docs run: | ai --apikey --sonnet --skip << 'EOF' > API.md Document all public APIs in src/api/: - Endpoints - Request/response schemas - Authentication requirements - Example usage Output in markdown format. EOF env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - name: Commit documentation run: | git config user.name "Documentation Bot" git config user.email "bot@example.com" git add ARCHITECTURE.md API.md git commit -m "docs: auto-generate from source" || exit 0 git push ``` ### Security Scanning ```yaml theme={null} name: Security Scan on: schedule: - cron: '0 2 * * *' # Daily at 2 AM workflow_dispatch: # Manual trigger jobs: security: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Install AIRun run: | curl -fsSL https://claude.ai/install.sh | bash git clone https://github.com/andisearch/airun.git cd airun && ./setup.sh - name: Run security audit run: | ai --apikey --opus --skip << 'EOF' > security-report.md Perform a comprehensive security audit: 1. Check for OWASP Top 10 vulnerabilities 2. Review authentication and authorization 3. Check for hardcoded secrets or credentials 4. Analyze dependency vulnerabilities (check package.json/requirements.txt) 5. Review API security (rate limiting, input validation) For each issue: - File path and line number - Severity (CRITICAL/HIGH/MEDIUM/LOW) - Explanation - Remediation steps EOF env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - name: Upload security report uses: actions/upload-artifact@v3 with: name: security-scan path: security-report.md - name: Check for critical issues run: | if grep -q "CRITICAL" security-report.md; then echo "::error::Critical security issues found!" exit 1 fi ``` ## GitLab CI ### Test Analysis Pipeline ```yaml theme={null} # .gitlab-ci.yml stages: - test - analyze test: stage: test image: node:20 script: - npm install - npm test artifacts: when: always paths: - test-results/ ai-analysis: stage: analyze image: node:20 script: - curl -fsSL https://claude.ai/install.sh | bash - git clone https://github.com/andisearch/airun.git - cd airun && ./setup.sh && cd .. - | ai --apikey --sonnet --skip << 'EOF' > analysis.md Analyze the test results in test-results/. Summarize pass/fail counts. For failures, identify root causes and suggest fixes. EOF artifacts: paths: - analysis.md variables: ANTHROPIC_API_KEY: $ANTHROPIC_API_KEY ``` ### Merge Request Review ```yaml theme={null} review-mr: stage: review image: node:20 script: - curl -fsSL https://claude.ai/install.sh | bash - git clone https://github.com/andisearch/airun.git - cd airun && ./setup.sh && cd .. - | ai --apikey --opus --skip << 'EOF' > review.md Review the changes in this merge request. Focus on security, performance, and code quality. Be specific with file paths and line numbers. EOF - | curl -X POST "$CI_API_V4_URL/projects/$CI_PROJECT_ID/merge_requests/$CI_MERGE_REQUEST_IID/notes" \ --header "PRIVATE-TOKEN: $GITLAB_TOKEN" \ --form "body= test-report.md Run the test suite and analyze results. Report pass/fail counts and explain any failures. EOF - store_artifacts: path: test-report.md workflows: test-and-analyze: jobs: - test-with-ai ``` ## Jenkins ```groovy theme={null} // Jenkinsfile pipeline { agent any environment { ANTHROPIC_API_KEY = credentials('anthropic-api-key') } stages { stage('Setup') { steps { sh 'curl -fsSL https://claude.ai/install.sh | bash' sh 'git clone https://github.com/andisearch/airun.git' sh 'cd airun && ./setup.sh' } } stage('Test and Analyze') { steps { sh ''' ai --apikey --sonnet --skip << 'EOF' > test-report.md Run the test suite (npm test). Analyze results and report findings. EOF ''' archiveArtifacts artifacts: 'test-report.md' } } } } ``` ## Docker Container Patterns ### Dockerfile for CI/CD ```dockerfile theme={null} FROM node:20-slim # Install Claude Code RUN curl -fsSL https://claude.ai/install.sh | bash # Install AIRun RUN git clone https://github.com/andisearch/airun.git && \ cd airun && \ ./setup.sh # Install jq for --live support RUN apt-get update && apt-get install -y jq && rm -rf /var/lib/apt/lists/* WORKDIR /workspace ENTRYPOINT ["ai"] ``` Usage: ```bash theme={null} # Build docker build -t airun-ci . # Run in CI docker run -v $(pwd):/workspace -e ANTHROPIC_API_KEY airun-ci \ --apikey --sonnet --skip << 'EOF' Run tests and analyze results. EOF ``` ### Docker Compose for Local Testing ```yaml theme={null} # docker-compose.yml services: airun: build: . volumes: - .:/workspace environment: - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY} command: | --apikey --sonnet --skip << 'EOF' Run the test suite and report results. EOF ``` ## Cost Optimization ### Choose the Right Model ```yaml theme={null} # Use Haiku for simple checks (cheapest) - name: Check formatting run: | ai --apikey --haiku --skip << 'EOF' Check if code follows formatting guidelines. Output: PASS or FAIL with specific issues. EOF # Use Sonnet for test analysis (balanced) - name: Analyze tests run: | ai --apikey --sonnet --skip << 'EOF' Run tests and analyze failures. EOF # Use Opus only for complex reviews (most expensive) - name: Security audit run: | ai --apikey --opus --skip << 'EOF' Comprehensive security audit. EOF ``` ### Cache Setup Between Jobs ```yaml theme={null} - name: Cache AIRun installation uses: actions/cache@v3 with: path: | ~/.ai-runner /usr/local/bin/ai key: airun-v1 - name: Install AIRun run: | if ! command -v ai &> /dev/null; then curl -fsSL https://claude.ai/install.sh | bash git clone https://github.com/andisearch/airun.git cd airun && ./setup.sh fi ``` ### Limit Analysis Scope ```yaml theme={null} # Only analyze changed files in PR - name: Review changed files only run: | CHANGED_FILES=$(git diff --name-only origin/main...HEAD | tr '\n' ' ') ai --apikey --sonnet --skip << EOF Review only these files: $CHANGED_FILES Focus on security and critical bugs. EOF ``` ## Security Best Practices ### 1. Never Commit Secrets ❌ **Bad:** ```yaml theme={null} env: ANTHROPIC_API_KEY: "sk-ant-api03-..." ``` ✅ **Good:** ```yaml theme={null} env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} ``` ### 2. Use Allowed Tools in Production ❌ **Bad (unlimited access):** ```bash theme={null} ai --skip dangerous-script.md ``` ✅ **Good (limited access):** ```bash theme={null} ai --allowedTools 'Read' 'Bash(npm test)' script.md ``` ### 3. Isolate in Containers ```yaml theme={null} jobs: analyze: runs-on: ubuntu-latest container: image: node:20 # All AI operations isolated in container ``` ### 4. Review Scripts Before CI Test scripts locally before adding to CI: ```bash theme={null} # Test locally first ai --apikey --skip script.md # Verify it does what you expect # Then add to CI ``` ## Troubleshooting ### Authentication Failures **Problem:** "Authentication failed" in CI. **Solution:** Verify secret is set: ```yaml theme={null} - name: Check API key run: | if [ -z "$ANTHROPIC_API_KEY" ]; then echo "::error::ANTHROPIC_API_KEY not set" exit 1 fi echo "API key length: ${#ANTHROPIC_API_KEY}" ``` ### Rate Limits **Problem:** Hitting API rate limits. **Solutions:** 1. **Use Haiku for simple tasks** (higher rate limits) 2. **Add delays between requests** 3. **Switch providers** when hitting limits: ```yaml theme={null} - name: Analyze (with fallback) run: | ai --apikey --sonnet --skip script.md || \ ai --aws --sonnet --skip script.md ``` ### Timeout Issues **Problem:** CI job times out. **Solution:** Add timeouts to AI commands: ```bash theme={null} timeout 5m ai --apikey --skip script.md ``` ## Next Steps Test analysis examples Automated review patterns Security best practices Configure API providers # Code Analysis Source: https://docs.airun.me/examples/code-analysis Analyze codebases with read-only access - no permission flags needed Analyze code architecture without modifying anything. This example shows how to use `--skip` for automation while keeping the analysis read-only. ## The Script ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip Summarize the architecture of this codebase. List the main entry points, key modules, and how data flows through the system. ``` From `examples/analyze-code.md`. Uses Sonnet for better code understanding. ## How It Works ### Model Selection: Sonnet ```bash theme={null} --sonnet ``` Sonnet is the balanced model tier: * **Better than Haiku** for code understanding and technical analysis * **Cheaper than Opus** - you don't need the most capable model for analysis * **Fast enough** for real-time exploration **When to use each model:** | Task | Model | Why | | -------------------------------------- | -------------- | ------------------------- | | Greet user, format text | `--haiku` | Simple text generation | | **Analyze code, run tests** | **`--sonnet`** | Balanced reasoning + cost | | Design architecture, complex debugging | `--opus` | Maximum reasoning power | ### The `--skip` Flag ```bash theme={null} --skip ``` This is shorthand for `--dangerously-skip-permissions`. It allows the AI to: * **Read files** without prompting you for each one * Use tools automatically * Explore the codebase freely Wait, isn't `--skip` dangerous? **Yes, but only for write operations.** This script's prompt is **read-only** - it only asks for analysis. The AI won't modify files unless your prompt tells it to. For true safety, use granular permissions: ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --allowedTools 'Read' 'Grep' 'Glob' Summarize the architecture of this codebase. ``` See [Permission Modes](/guides/permissions) for production patterns. ### The Prompt ``` Summarize the architecture of this codebase. List the main entry points, key modules, and how data flows through the system. ``` The prompt is specific about what to analyze: * **Main entry points** - where execution starts * **Key modules** - important components * **Data flow** - how information moves through the system The more specific your prompt, the better the analysis. ## Running the Script ### Analyze any codebase ```bash theme={null} # Make it executable chmod +x analyze-code.md # Run in any project directory cd ~/projects/my-app ./analyze-code.md ``` The AI will: 1. Explore the directory structure 2. Read key files (package.json, main entry points, etc.) 3. Analyze the architecture 4. Summarize findings ### Override the provider ```bash theme={null} # Use AWS Bedrock instead ai --aws analyze-code.md # Use Opus for deeper analysis ai --opus analyze-code.md # Use local Ollama (free!) ai --ollama analyze-code.md ``` ### Save output to file ```bash theme={null} ./analyze-code.md > architecture-summary.txt ``` Only the AI's response is saved (not status messages). ## Real-World Usage ### Quick Project Overview When joining a new codebase: ```bash theme={null} cd ~/projects/new-repo ./analyze-code.md > ARCHITECTURE.md ``` You now have a generated architecture document. ### Compare Multiple Projects ```bash theme={null} for dir in project-*; do cd "$dir" echo "# $dir" >> ../analysis.txt ../analyze-code.md >> ../analysis.txt cd .. done ``` ### CI/CD Documentation Generate architecture docs automatically: ```yaml theme={null} # .github/workflows/docs.yml name: Update Architecture Docs on: push: branches: [main] jobs: analyze: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Analyze codebase run: | curl -fsSL https://claude.ai/install.sh | bash git clone https://github.com/andisearch/airun.git cd airun && ./setup.sh cd .. ai --apikey --sonnet --skip << 'EOF' > ARCHITECTURE.md Summarize this codebase architecture. List main entry points, key modules, and data flow. EOF env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - name: Commit changes run: | git config user.name "Architecture Bot" git config user.email "bot@example.com" git add ARCHITECTURE.md git commit -m "docs: update architecture" || true git push ``` ## Customizing the Analysis ### Focus on Specific Aspects **Security analysis:** ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip Analyze this codebase for security issues. Check for: - SQL injection vulnerabilities - XSS vulnerabilities - Authentication/authorization flaws - Sensitive data exposure Be specific about file paths and line numbers. ``` **Performance analysis:** ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip Analyze this codebase for performance issues: - Inefficient algorithms (O(n²) or worse) - Unnecessary re-renders - Memory leaks - Large bundle size contributors ``` **Test coverage analysis:** ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip Analyze test coverage in this codebase: - Which modules have tests? - Which critical paths are untested? - Are there obsolete tests? - Suggest priority areas for new tests. ``` ### Limit Scope ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip Analyze only the API layer in src/api/. Document: - Available endpoints - Request/response schemas - Authentication requirements ``` ## Why `--skip` Works Here This script uses `--skip` even though it's read-only because: 1. **Automation** - No permission prompts when reading files 2. **Speed** - The AI explores freely without asking 3. **Safe prompt** - The prompt never asks to modify anything The risk comes from the **prompt**, not the flag. A read-only prompt with `--skip` is safe. **For production scripts**, prefer explicit tool allowlists: ```bash theme={null} --allowedTools 'Read' 'Grep' 'Glob' ``` This prevents accidents if someone modifies your prompt later. ## Next Steps Run commands and report results Automated security and quality scanning Run AIRun in GitHub Actions and GitLab CI Permission modes and security patterns # Automated Code Review Source: https://docs.airun.me/examples/code-review Security scanning, quality checks, and automated PR reviews Automate code review workflows with AI-powered analysis. This guide shows patterns for security scanning, quality checks, and automated PR reviews. ## Basic Code Review Script ```markdown theme={null} #!/usr/bin/env -S ai --opus --skip Review the code in this repository for security vulnerabilities. Focus on OWASP Top 10 issues. Be specific about file and line numbers. ``` **Model choice:** Use `--opus` for code reviews. The most capable model finds more issues and provides better explanations. ## Security Scanning ### Comprehensive Security Audit ```markdown theme={null} #!/usr/bin/env -S ai --opus --skip Perform a comprehensive security audit of this codebase: 1. OWASP Top 10 vulnerabilities: - SQL injection - XSS (cross-site scripting) - CSRF (cross-site request forgery) - Authentication/authorization flaws - Security misconfiguration - Sensitive data exposure - Insecure deserialization - Components with known vulnerabilities 2. Code-specific issues: - Hardcoded secrets or credentials - Insufficient input validation - Insecure cryptographic practices - Race conditions and concurrency issues 3. Dependency vulnerabilities: - Check package.json/requirements.txt/Cargo.toml - Flag packages with known CVEs For each issue: - File path and line number - Severity: CRITICAL / HIGH / MEDIUM / LOW - Explanation of the vulnerability - Specific remediation steps - Example of secure code Prioritize issues by severity. ``` **Usage:** ```bash theme={null} chmod +x security-audit.md ./security-audit.md > security-report.md ``` ### Focused Security Checks **Authentication review:** ```markdown theme={null} #!/usr/bin/env -S ai --opus --skip Review authentication and authorization in this codebase: 1. Authentication mechanisms: - Password storage (are passwords hashed with bcrypt/argon2?) - Session management (secure tokens?) - JWT implementation (if used) 2. Authorization checks: - Are permissions checked before sensitive operations? - Any missing authorization checks? - Privilege escalation risks? 3. Common auth vulnerabilities: - Broken authentication - Missing rate limiting on login - Insecure password reset flows - Session fixation Be specific with file paths and line numbers. ``` **Data validation review:** ```markdown theme={null} #!/usr/bin/env -S ai --opus --skip Review input validation and data sanitization: 1. API endpoints: - Is user input validated? - Are query parameters sanitized? - Are file uploads restricted? 2. Database queries: - Any raw SQL with user input? (SQL injection risk) - Are ORMs used properly? 3. XSS prevention: - Is user content escaped before rendering? - Are Content Security Policies configured? Flag any inputs that reach dangerous sinks without validation. ``` **Secrets detection:** ```markdown theme={null} #!/usr/bin/env -S ai --haiku --skip Scan for hardcoded secrets and credentials: 1. Search for patterns: - API keys (sk-, pk-, api_key) - Passwords (password=, pwd=) - Database connection strings - Private keys - OAuth tokens 2. Check common locations: - Source code files - Configuration files - Environment files (.env, .env.example) - Docker files - Scripts 3. Also check git history for accidentally committed secrets. Output: File path, line number, type of secret found. ``` ## Code Quality Reviews ### General Quality Audit ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip Review code quality and maintainability: 1. Code organization: - Is the code well-structured? - Are responsibilities clearly separated? - Are naming conventions consistent? 2. Common issues: - Code duplication - Long functions (>50 lines) - High cyclomatic complexity - Unclear variable names - Missing error handling 3. Best practices: - Are design patterns used appropriately? - Is error handling consistent? - Are edge cases handled? - Is logging sufficient for debugging? 4. Technical debt: - TODO comments and their priority - Deprecated API usage - Outdated patterns Prioritize by impact on maintainability. ``` ### Performance Review ```markdown theme={null} #!/usr/bin/env -S ai --opus --skip Review code for performance issues: 1. Algorithm efficiency: - Identify O(n²) or worse algorithms - Nested loops on large datasets - Unnecessary iterations 2. Database performance: - N+1 query problems - Missing indexes - Large result sets without pagination - Unnecessary joins 3. Frontend performance: - Large bundle size - Unnecessary re-renders - Missing memoization - Large images without optimization 4. Resource usage: - Memory leaks - File handles not closed - Connection pool exhaustion For each issue, estimate performance impact and suggest optimizations. ``` ### Test Coverage Review ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip Analyze test coverage and quality: 1. Coverage analysis: - Which modules have tests? - Which critical paths are untested? - What's the approximate coverage percentage? 2. Test quality: - Are tests meaningful or just for coverage? - Are edge cases tested? - Are error paths tested? - Are integration tests present? 3. Gaps: - Critical functionality without tests - Recent changes without test updates - Brittle tests that break often 4. Recommendations: - Priority areas for new tests - Tests that could be simplified - Missing test types (unit/integration/e2e) ``` ## Pull Request Reviews ### Automated PR Review ```markdown theme={null} #!/usr/bin/env -S ai --opus --skip Review the changes in this pull request: 1. Security: - New vulnerabilities introduced? - Security best practices followed? - Input validation for new endpoints? 2. Code quality: - Is the code clear and maintainable? - Are naming conventions followed? - Is error handling adequate? 3. Performance: - Any performance regressions? - Database queries optimized? - Resource usage concerns? 4. Testing: - Are new features tested? - Do existing tests still pass? - Are edge cases covered? 5. Documentation: - Is new functionality documented? - Are comments clear and helpful? - README updated if needed? For each issue: - File path and line number - Severity: BLOCKER / MAJOR / MINOR - Explanation - Suggested fix Use this format: **[SEVERITY] Issue description** File: `path/to/file.ts:42` Problem: [explanation] Suggestion: [how to fix] ``` **Usage in GitHub Actions:** ```yaml theme={null} name: AI PR Review on: pull_request: types: [opened, synchronize] jobs: review: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: fetch-depth: 0 - name: Install AIRun run: | curl -fsSL https://claude.ai/install.sh | bash git clone https://github.com/andisearch/airun.git cd airun && ./setup.sh - name: Run AI review run: | ai --apikey --opus --skip << 'EOF' > review.md Review the changes in this pull request. Focus on security, quality, and performance. Be specific with file paths and line numbers. EOF env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - name: Comment on PR uses: actions/github-script@v6 with: script: | const fs = require('fs'); const review = fs.readFileSync('review.md', 'utf8'); github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: `## 🤖 AI Code Review\n\n${review}` }); ``` ### Review Only Changed Files More efficient for large repos: ```markdown theme={null} #!/usr/bin/env -S ai --opus --skip Review only the files that changed in this PR. Run: git diff --name-only origin/main...HEAD For each changed file: 1. Read the current version 2. Identify what changed 3. Review for security, quality, performance issues Focus on: - New vulnerabilities introduced - Breaking changes - Performance regressions - Missing tests for new code Output format: **File: path/to/file** - Issue 1... - Issue 2... ``` ## Provider Selection for Reviews ### When to Use Each Provider | Review Type | Provider | Model | Why | | --------------------- | ---------- | ----------- | ------------------------------------- | | **Security audit** | `--apikey` | `--opus` | Most thorough vulnerability detection | | **Quick PR review** | `--apikey` | `--sonnet` | Balanced speed and quality | | **Simple checks** | `--apikey` | `--haiku` | Fast, cheap for simple patterns | | **Large enterprise** | `--aws` | `--opus` | AWS compliance, control | | **Free tier testing** | `--ollama` | local model | No API costs | ### Cost Optimization Review only what matters: ```bash theme={null} # Cheap: Check formatting and simple patterns ai --haiku --skip format-check.md # Medium: Review test files ai --sonnet --skip test-review.md # Expensive: Deep security audit ai --opus --skip security-audit.md ``` ## Language-Specific Reviews ### JavaScript/TypeScript ```markdown theme={null} #!/usr/bin/env -S ai --opus --skip Review this TypeScript/JavaScript codebase: 1. TypeScript usage: - Are types used effectively? - Any `any` types that should be specific? - Missing type definitions? 2. JavaScript patterns: - Async/await used correctly? - Promise rejections handled? - Event listeners cleaned up? - Memory leaks in closures? 3. React-specific (if applicable): - Unnecessary re-renders? - Missing useCallback/useMemo? - State management issues? - Key props on lists? 4. Node.js-specific (if applicable): - Async errors caught? - Streams handled properly? - Process signals handled? ``` ### Python ```markdown theme={null} #!/usr/bin/env -S ai --opus --skip Review this Python codebase: 1. Python idioms: - PEP 8 compliance - List comprehensions vs loops - Context managers for resources - Proper exception handling 2. Type hints: - Are type hints used? - Are they accurate? 3. Django/Flask-specific (if applicable): - ORM queries optimized? - CSRF protection enabled? - SQL injection prevention? - Proper session management? 4. Common issues: - Mutable default arguments - Global state - Resource leaks ``` ### Rust ```markdown theme={null} #!/usr/bin/env -S ai --opus --skip Review this Rust codebase: 1. Safety: - Unsafe blocks justified? - Memory safety concerns? - Thread safety issues? 2. Rust idioms: - Ownership used effectively? - Borrowing patterns clear? - Error handling with Result? - Iterator chains vs loops? 3. Performance: - Unnecessary allocations? - Clone overuse? - Missing zero-cost abstractions? 4. API design: - Ergonomic public APIs? - Proper use of traits? ``` ## Combining Multiple Review Types Run multiple focused reviews in parallel: ```bash theme={null} #!/bin/bash # comprehensive-review.sh # Run reviews in parallel ai --opus --skip security-audit.md > reports/security.md & ai --sonnet --skip quality-review.md > reports/quality.md & ai --sonnet --skip performance-review.md > reports/performance.md & ai --sonnet --skip test-coverage.md > reports/tests.md & # Wait for all to complete wait # Combine reports cat reports/*.md > full-review.md echo "Review complete: full-review.md" ``` ## Filtering and Prioritization Focus reviews on what matters: ```markdown theme={null} #!/usr/bin/env -S ai --opus --skip Security review focused on HIGH and CRITICAL issues only. Ignore: - Minor style issues - Low-severity findings - Non-security concerns Focus on: - Authentication/authorization flaws - SQL injection - XSS vulnerabilities - Hardcoded secrets - Insecure cryptography Only report issues that pose real security risk. ``` ## Integration with Code Review Tools ### GitHub Code Review Comments Post line-specific comments: ```python theme={null} #!/usr/bin/env python3 # post-review-comments.py import os import subprocess from github import Github # Get AI review review = subprocess.check_output([ 'ai', '--opus', '--skip', 'review-script.md' ]).decode('utf-8') # Parse review for file:line issues # Format: File: path/to/file.ts:42 issues = parse_review(review) # Your parser # Post to GitHub g = Github(os.getenv('GITHUB_TOKEN')) repo = g.get_repo(os.getenv('GITHUB_REPOSITORY')) pr = repo.get_pull(int(os.getenv('PR_NUMBER'))) for issue in issues: pr.create_review_comment( body=issue['comment'], path=issue['file'], line=issue['line'] ) ``` ### GitLab Merge Request Comments Similar pattern for GitLab: ```bash theme={null} # Post review to GitLab MR REVIEW=$(ai --opus --skip review.md) curl -X POST "$CI_API_V4_URL/projects/$CI_PROJECT_ID/merge_requests/$CI_MERGE_REQUEST_IID/notes" \ --header "PRIVATE-TOKEN: $GITLAB_TOKEN" \ --form "body=$REVIEW" ``` ## Next Steps Automate reviews in CI/CD Security best practices Automated testing workflows Advanced scripting patterns # Data Processing Source: https://docs.airun.me/examples/data-processing Process JSON, CSV, and logs with AI-powered pipelines Build data processing pipelines with AIRun. Transform, analyze, and enrich data using AI, with full Unix pipe support. ## Basic Patterns ### Process JSON Data ```markdown theme={null} #!/usr/bin/env -S ai --haiku Analyze the JSON data provided on stdin. Summarize key metrics and flag any anomalies. ``` ```bash theme={null} cat metrics.json | ./analyze.md ``` **Input (metrics.json):** ```json theme={null} { "date": "2026-03-03", "users": 1500, "revenue": 45000, "signups": 120, "churn": 8, "response_times_ms": [120, 150, 890, 130, 125] } ``` **Output:** ``` Metrics Summary for 2026-03-03: - Active users: 1,500 - Revenue: $45,000 ($30/user) - Growth: 120 signups, 8 churn (93.3% retention) Anomaly Detected: - Response time spike: 890ms (7x normal) - Other requests: 120-150ms (healthy) - Action: Investigate slow query/endpoint ``` ### Transform Data Format ```markdown theme={null} #!/usr/bin/env -S ai --haiku Convert the JSON data on stdin to CSV format. Include all fields as columns. ``` ```bash theme={null} cat data.json | ./json-to-csv.md > data.csv ``` ### Filter and Aggregate ```markdown theme={null} #!/usr/bin/env -S ai --haiku The stdin contains JSON with an array of transactions. Filter for transactions > $1000. Output: total count and sum. ``` ```bash theme={null} cat transactions.json | ./filter-sum.md # Output: 47 transactions totaling $87,340 ``` ## Pipeline Patterns ### Multi-Stage Processing Chain multiple AI scripts together: ```bash theme={null} # Extract → Analyze → Format pipeline ./extract-data.md | ./analyze.md | ./format-report.md > report.txt ``` **extract-data.md:** ```markdown theme={null} #!/usr/bin/env -S ai --haiku --skip Read metrics.json and output only: - users - revenue - signups - churn Format as CSV (no headers). ``` **analyze.md:** ```markdown theme={null} #!/usr/bin/env -S ai --haiku The stdin contains CSV: users,revenue,signups,churn Calculate: - Revenue per user - Retention rate - Growth rate Output: One line summary. ``` **format-report.md:** ```markdown theme={null} #!/usr/bin/env -S ai --haiku Format the analysis from stdin as a professional email to executives. Keep it under 3 paragraphs. ``` ### Parallel Processing Process multiple files concurrently: ```bash theme={null} #!/bin/bash # process-all.sh for file in data/*.json; do cat "$file" | ./analyze.md > "results/$(basename "$file" .json).txt" & done wait echo "Processed $(ls results/ | wc -l) files" ``` ## Real-World Use Cases ### API Response Analysis ```markdown theme={null} #!/usr/bin/env -S ai --haiku Analyze the API response on stdin (JSON format): 1. Response structure validity 2. Expected fields present? 3. Data types correct? 4. Any error indicators? 5. Performance metrics (if present) Output: VALID or INVALID with explanation. ``` ```bash theme={null} # Test API endpoint curl -s https://api.example.com/v1/users | ./validate-response.md ``` ### Log Analysis ```markdown theme={null} #!/usr/bin/env -S ai --sonnet Analyze the nginx access logs on stdin: 1. Request volume and patterns 2. Top 10 endpoints by traffic 3. Error rate (4xx, 5xx) 4. Response time distribution 5. Unusual patterns or potential attacks Focus on actionable insights. ``` ```bash theme={null} tail -1000 /var/log/nginx/access.log | ./analyze-logs.md ``` ### Database Query Results ```markdown theme={null} #!/usr/bin/env -S ai --haiku Analyze the database query results on stdin (CSV format). Identify: - Trends in the data - Outliers - Missing or null values - Data quality issues Suggest next steps for data cleanup. ``` ```bash theme={null} psql -d mydb -c "SELECT * FROM metrics WHERE date > NOW() - INTERVAL '7 days'" \ --csv | ./analyze-db-results.md ``` ### Git History Analysis ```markdown theme={null} #!/usr/bin/env -S ai --haiku Analyze the git commit history on stdin: 1. Most active areas of the codebase 2. Commit message quality 3. Commit frequency patterns 4. Authors and contribution patterns 5. Any concerning trends? ``` ```bash theme={null} git log --oneline --numstat -100 | ./analyze-commits.md ``` ## Data Transformation Recipes ### JSON to Markdown Table ```markdown theme={null} #!/usr/bin/env -S ai --haiku Convert the JSON array on stdin to a Markdown table. Auto-detect columns from the first object. Format numbers with proper separators. ``` ```bash theme={null} cat users.json | ./json-to-table.md > users-table.md ``` **Input:** ```json theme={null} [ {"name": "Alice", "sales": 45000, "region": "West"}, {"name": "Bob", "sales": 38000, "region": "East"} ] ``` **Output:** ```markdown theme={null} | Name | Sales | Region | |-------|---------|--------| | Alice | 45,000 | West | | Bob | 38,000 | East | ``` ### CSV Cleanup ```markdown theme={null} #!/usr/bin/env -S ai --haiku Clean the CSV data on stdin: 1. Remove duplicate rows 2. Fix inconsistent formatting 3. Handle missing values (use "N/A") 4. Standardize date formats to YYYY-MM-DD 5. Trim whitespace Output: Cleaned CSV. ``` ```bash theme={null} cat messy-data.csv | ./clean-csv.md > clean-data.csv ``` ### Data Enrichment ```markdown theme={null} #!/usr/bin/env -S ai --sonnet Enrich the user data on stdin (CSV). For each row: 1. Read: user_id, email, signup_date 2. Infer: likely timezone from email domain 3. Calculate: days since signup 4. Determine: user lifecycle stage (new/active/at-risk) Output: Enriched CSV with new columns. ``` ```bash theme={null} cat users.csv | ./enrich-users.md > users-enriched.csv ``` ### Anomaly Detection ```markdown theme={null} #!/usr/bin/env -S ai --sonnet Detect anomalies in the time-series data on stdin (CSV). Columns: timestamp, value Use statistical methods: - 3-sigma rule for outliers - Moving average for trend - Sudden spikes or drops Output: CSV with only anomalous rows + explanation column. ``` ```bash theme={null} cat timeseries.csv | ./detect-anomalies.md > anomalies.csv ``` ## Advanced Patterns ### Streaming Large Files Process large files in chunks: ```bash theme={null} #!/bin/bash # process-large-file.sh # Process 1000 lines at a time split -l 1000 large-file.csv chunks/chunk- for chunk in chunks/chunk-*; do cat "$chunk" | ./analyze.md >> results.txt rm "$chunk" done echo "Processing complete" ``` ### Live Streaming with --live ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --live Analyze the log stream on stdin. Print a summary every 100 lines: - Error count - Warning count - Unusual patterns Continue until EOF. ``` ```bash theme={null} tail -f /var/log/app.log | ./stream-analyze.md ``` ### Multi-Source Aggregation ```bash theme={null} #!/bin/bash # aggregate-sources.sh # Fetch from multiple sources curl -s https://api1.example.com/metrics > /tmp/source1.json & curl -s https://api2.example.com/stats > /tmp/source2.json & wait # Combine and analyze jq -s '.[0] + .[1]' /tmp/source1.json /tmp/source2.json | \ ./analyze-combined.md > report.txt ``` ### Error Recovery ```bash theme={null} #!/bin/bash # process-with-retry.sh MAX_RETRIES=3 RETRY=0 while [ $RETRY -lt $MAX_RETRIES ]; do if cat data.json | ./process.md > output.txt 2>error.log; then echo "Success" exit 0 fi RETRY=$((RETRY + 1)) echo "Attempt $RETRY failed, retrying..." sleep 2 done echo "Failed after $MAX_RETRIES attempts" exit 1 ``` ## Data Processing in CI/CD ### Daily Metrics Analysis ```yaml theme={null} # .github/workflows/daily-metrics.yml name: Daily Metrics Analysis on: schedule: - cron: '0 1 * * *' # 1 AM daily jobs: analyze: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Install AIRun run: | curl -fsSL https://claude.ai/install.sh | bash git clone https://github.com/andisearch/airun.git cd airun && ./setup.sh - name: Fetch and analyze metrics run: | curl -s https://api.example.com/daily-metrics | \ ai --apikey --haiku << 'EOF' > daily-report.md Analyze the daily metrics JSON on stdin. Compare to typical values. Flag any anomalies. EOF env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - name: Email report uses: dawidd6/action-send-mail@v3 with: server_address: smtp.gmail.com server_port: 465 username: ${{ secrets.MAIL_USERNAME }} password: ${{ secrets.MAIL_PASSWORD }} subject: Daily Metrics Report body: file://daily-report.md to: team@example.com ``` ### Process S3 Data ```bash theme={null} #!/bin/bash # process-s3-data.sh # Download from S3 aws s3 cp s3://my-bucket/data/latest.json - | \ ai --apikey --haiku --skip << 'EOF' > summary.txt Analyze the JSON data on stdin. Generate a one-paragraph summary. EOF # Upload results aws s3 cp summary.txt s3://my-bucket/reports/$(date +%Y%m%d).txt ``` ## Cost Optimization ### Choose the Right Model | Task | Model | Why | | ------------------------------- | ---------- | ------------------ | | Simple CSV transformations | `--haiku` | Fast, cheap | | Log analysis, anomaly detection | `--sonnet` | Balanced reasoning | | Complex data modeling | `--opus` | Deep analysis | ```bash theme={null} # Cheap: Simple format conversion cat data.json | ai --haiku json-to-csv.md # Balanced: Anomaly detection cat metrics.csv | ai --sonnet detect-anomalies.md # Expensive: Complex statistical analysis cat dataset.csv | ai --opus deep-analysis.md ``` ### Batch Processing Process multiple files in one prompt (saves API calls): ```markdown theme={null} #!/usr/bin/env -S ai --haiku --skip Analyze all JSON files in data/ directory. For each file: 1. Read contents 2. Extract key metrics 3. One-line summary Output: Markdown list of summaries. ``` ```bash theme={null} ./analyze-all.md > summary.md ``` ## Monitoring and Logging ### Pipeline with Status Tracking ```bash theme={null} #!/bin/bash # monitored-pipeline.sh log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a pipeline.log; } log "Starting data processing pipeline" log "Stage 1: Extract data" if ! ./extract.md > stage1.json 2>>pipeline.log; then log "ERROR: Stage 1 failed" exit 1 fi log "Stage 2: Transform data" if ! cat stage1.json | ./transform.md > stage2.csv 2>>pipeline.log; then log "ERROR: Stage 2 failed" exit 1 fi log "Stage 3: Generate report" if ! cat stage2.csv | ./report.md > final-report.md 2>>pipeline.log; then log "ERROR: Stage 3 failed" exit 1 fi log "Pipeline complete: final-report.md" ``` ### Health Checks ```markdown theme={null} #!/usr/bin/env -S ai --haiku Validate the data pipeline output on stdin (JSON). Checks: 1. Valid JSON structure 2. Required fields present: [timestamp, value, status] 3. No null values 4. Timestamp in ISO 8601 format 5. Status in [active, pending, completed] Output: PASS or FAIL with specific issues. ``` ```bash theme={null} cat output.json | ./validate.md || echo "Pipeline validation failed!" ``` ## Troubleshooting ### Empty Output **Problem:** Pipeline produces empty files. **Debug:** ```bash theme={null} # Check each stage cat input.json | tee /dev/stderr | ./process.md | tee /dev/stderr > output.txt ``` ### Data Loss in Pipeline **Problem:** Data disappears between stages. **Solution:** Save intermediate results: ```bash theme={null} ./stage1.md > stage1.out cat stage1.out | ./stage2.md > stage2.out cat stage2.out | ./stage3.md > final.out ``` ### Encoding Issues **Problem:** Special characters corrupted. **Solution:** Force UTF-8: ```bash theme={null} export LC_ALL=en_US.UTF-8 cat data.json | ./process.md > output.txt ``` ## Next Steps Unix pipe fundamentals Automate data pipelines Process data in real-time Advanced pipeline patterns # Hello World Source: https://docs.airun.me/examples/hello-world The simplest AIRun script - your first executable prompt The simplest possible AIRun script. This example shows the basic shebang syntax and how to make a markdown file executable. ## The Script ```markdown theme={null} #!/usr/bin/env -S ai --haiku Say hello and briefly explain what you can do. ``` This is the complete script from `examples/hello.md`. It's only 2 lines! ## How It Works ### The Shebang Line ```bash theme={null} #!/usr/bin/env -S ai --haiku ``` This line tells your system how to run the file: * `#!/usr/bin/env` - Standard Unix shebang for finding executables in PATH * `-S` - **Essential flag** that allows passing arguments (like `--haiku`) to the command * `ai` - The AIRun command * `--haiku` - Use the fastest, cheapest model tier (perfect for simple tasks) You **must** use `-S` when passing flags in a shebang. Without it, `env` treats `ai --haiku` as a single command name and fails. **Works:** `#!/usr/bin/env -S ai --haiku` **Fails:** `#!/usr/bin/env ai --haiku` ### The Prompt Everything after the shebang is your prompt: ``` Say hello and briefly explain what you can do. ``` No special syntax needed - just write what you want the AI to do. ## Running the Script ### Method 1: Make it executable and run directly ```bash theme={null} # Make the file executable chmod +x hello.md # Run it ./hello.md ``` The shebang tells your system to use `ai --haiku` to execute the file. ### Method 2: Run with the ai command ```bash theme={null} # Shebang flags are still honored ai hello.md ``` ### Method 3: Override the model ```bash theme={null} # Use Sonnet instead of Haiku (CLI overrides shebang) ai --sonnet hello.md # Use a different provider ai --aws --opus hello.md ``` **Flag precedence:** CLI flags > shebang flags > saved defaults Running `ai --sonnet hello.md` overrides the `--haiku` in the shebang. ## Why Use Haiku? This script uses `--haiku` because: * **Fastest** - Haiku responds in milliseconds * **Cheapest** - Lowest cost per token * **Sufficient** - Simple text generation doesn't need Opus **Model selection guide:** | Task | Model | | -------------------------------------- | ---------- | | Simple text, greetings, summaries | `--haiku` | | Code analysis, test running | `--sonnet` | | Complex reasoning, architecture design | `--opus` | ## Creating Your Own Create a new script: ```bash theme={null} cat > greet.md << 'EOF' #!/usr/bin/env -S ai --haiku Write a friendly greeting and tell me a fun fact about AI. EOF chmod +x greet.md ./greet.md ``` ## Read-Only by Default This script doesn't need any permission flags because it only generates text. It cannot: * Write files * Run commands * Modify your system For scripts that need to take actions, see: * [Test Automation](/examples/test-automation) - Using `--skip` for running commands * [Code Analysis](/examples/code-analysis) - Read-only analysis without permissions ## Next Steps Analyze codebases without modifying anything Add customizable parameters to scripts Run commands and report results Complete guide to executable markdown # Live Streaming Output Source: https://docs.airun.me/examples/live-streaming Stream AI progress in real-time for long-running scripts See AI output as it's generated, not just when complete. This example shows how `--live` streams progress for long-running scripts. ## The Script ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip --live Explore this repository and write a short summary of what it does, its key features, and how to get started. Print your findings as you go. Finally, generate a concise report in markdown format. ``` From `examples/live-report.md`. Note the key phrase: **"Print your findings as you go."** ## How It Works ### The `--live` Flag ```bash theme={null} --live ``` Enables real-time streaming of AI output. Instead of waiting for the full response, you see text appear as the AI writes it. **Without `--live`:** ```bash theme={null} ./script.md # (silence for 30 seconds) # Then all output appears at once ``` **With `--live`:** ```bash theme={null} ./script.md # (starts streaming immediately) I'll explore the repository structure... Found a Node.js project with TypeScript... Looking at package.json to identify dependencies... Now examining the main entry point... # (output continues in real-time) ``` ### How Streaming Works `--live` streams at **turn granularity** - each time Claude writes text between tool calls, that text appears immediately. **Critical insight:** The AI must be prompted to narrate its progress, otherwise it may work silently using tools and only output text at the end. **Streams incrementally:** ``` Print your findings as you go. ``` **No intermediate output:** ``` Explore this repository and write a summary. ``` Both produce the same final result, but only the first streams progress. ### Prompting for Live Output Use these phrases to get streaming output: * **"Print as you go"** * **"Report findings as you discover them"** * **"Describe each step"** * **"Narrate your progress"** * **"Step by step, explain what you find"** These prompt the AI to write text between tool calls, giving `--live` something to stream. ## Running the Script ### Basic Usage ```bash theme={null} # Make it executable chmod +x live-report.md # Run it ./live-report.md ``` You'll see output stream in real-time: ``` [AI Runner] Using: Claude Code + Claude Pro [AI Runner] Model: Sonnet 4.6 I'll start by exploring the repository structure to understand the project. This appears to be a Node.js project with TypeScript. I can see: - Package.json indicating it's called "airun" - TypeScript configuration files - A src/ directory with the main source code Let me examine the key files to understand what it does... (output continues streaming) ``` ### Save Output to File ```bash theme={null} ./live-report.md > report.md ``` When stdout is redirected, `--live` automatically separates narration from content: **Console (stderr) - streams in real-time:** ``` [AI Runner] Using: Claude Code + Claude Pro [AI Runner] Model: Sonnet 4.6 I'll explore the repository structure and key files... Now let me look at the core scripts and provider structure. Here's my report: [AI Runner] Done (70 lines written) ``` **File (stdout) - clean content only:** ```markdown theme={null} # AIRun Project Summary ## Overview AIRun is a tool for running AI prompts like programs... ## Key Features - Executable markdown with shebang support - Cross-cloud provider switching - Unix pipe support ... ``` How it works: * Intermediate turns (narration) → **stderr** (appears on console) * Last turn content → **stdout** (saved to file) * The last turn is split at the first markdown heading or YAML frontmatter * Only the structured content goes to the file ### Override Model or Provider ```bash theme={null} # Use Opus for deeper analysis ai --opus live-report.md # Use AWS Bedrock ai --aws --sonnet live-report.md # Use local Ollama ai --ollama live-report.md ``` ### Suppress Status Messages For CI/CD where you only want clean output: ```bash theme={null} ai --quiet live-report.md > report.md ``` No status messages, just the final report saved to the file. ## Real-World Usage ### Repository Documentation Generate README documentation with live progress: ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip --live Explore this repository and generate a comprehensive README.md: 1. Project overview and purpose 2. Installation instructions 3. Usage examples 4. API documentation 5. Contributing guidelines Print a status update after examining each major directory. Finally, output the complete README in markdown format. ``` ```bash theme={null} chmod +x generate-readme.md ./generate-readme.md > README.md ``` You'll see progress on console, clean README saved to file. ### Onboarding New Team Members ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip --live Create an onboarding guide for new developers: 1. Describe the codebase structure 2. Explain the development workflow 3. List the key technologies used 4. Identify the most important files to read first 5. Suggest a learning path Narrate your exploration as you go through the codebase. Finally, generate a structured onboarding document. ``` ### Security Audit with Progress ```markdown theme={null} #!/usr/bin/env -S ai --opus --skip --live Perform a security audit of this codebase: 1. Check for common vulnerabilities (OWASP Top 10) 2. Review authentication and authorization 3. Examine data validation 4. Check for exposed secrets or credentials 5. Review dependencies for known vulnerabilities Report findings as you examine each area. Finally, generate a prioritized security report. ``` ### Long-Running Test Suites ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip --live Run the full test suite including integration tests. Print a status update after each test file completes: - File name - Pass/fail count - Time taken At the end, provide a summary with: - Total pass/fail counts - Slowest tests - Root cause analysis for failures ``` ## Browser Automation with Live Progress Combine `--live` with `--chrome` for browser testing: ```markdown theme={null} #!/usr/bin/env -S ai --skip --chrome --live Test the user registration flow: 1. Navigate to the signup page 2. Fill in the registration form 3. Submit and verify email sent 4. Follow email link to activate account 5. Login with new credentials Narrate each step as you complete it. Report any issues found. ``` ```bash theme={null} chmod +x test-signup.md ./test-signup.md ``` You'll see each step as it happens: ``` Navigating to https://app.example.com/signup... Filling in the registration form... Submitting the form... Checking for success message... ✓ Registration successful Looking for confirmation email... ``` ## Output Redirection Patterns ### Narration to Console, Content to File This is the default behavior when redirecting: ```bash theme={null} ./live-report.md > report.md ``` * Narration streams to console (stderr) * Clean report saved to file (stdout) ### Everything to File (No Console Output) ```bash theme={null} ./live-report.md > report.md 2>&1 ``` Both stdout and stderr go to the file. ### Only Status Messages (No Content) ```bash theme={null} ./live-report.md > /dev/null ``` See progress on console, discard the final report. ### Separate Files for Narration and Content ```bash theme={null} ./live-report.md > report.md 2> progress.log ``` * Clean report → `report.md` * Progress narration → `progress.log` ## Requirements `--live` requires `jq` to be installed: ```bash theme={null} # macOS brew install jq # Ubuntu/Debian sudo apt install jq # Fedora sudo dnf install jq ``` If `jq` is not installed, AIRun will fall back to non-streaming output and show a warning. ## When to Use `--live` Use `--live` for: * **Long-running scripts** (>30 seconds) where you want to see progress * **Browser automation** to see each step as it happens * **Test suites** to see results as tests complete * **Repository exploration** to understand what the AI is examining * **CI/CD** to get real-time build logs Don't use `--live` for: * **Quick scripts** (under 10 seconds) where streaming adds no value * **Pipe chains** where you're piping to another script * **JSON output** where structured data is needed ## Combining with Other Flags ### Live + Quiet (CI/CD) ```bash theme={null} ai --live --quiet script.md > output.txt ``` Streaming to stdout, no status messages on stderr. Good for CI/CD logs. ### Live + Variables ```markdown theme={null} #!/usr/bin/env -S ai --live --skip --- vars: target: "authentication" --- Audit the {{target}} system. Print findings as you discover them. ``` ```bash theme={null} ./audit.md --target "payment processing" ``` ### Live + Provider Override ```bash theme={null} # Script has --live in shebang, override provider from CLI ai --aws --opus script.md ``` ## Troubleshooting ### No Intermediate Output **Problem:** Using `--live` but only seeing output at the end. **Solution:** Add narration phrases to your prompt: ```diff theme={null} - Explore this repository and write a summary. + Explore this repository. Print your findings as you go. + Finally, write a summary. ``` ### Output Not Streaming to Console **Problem:** Output appears all at once instead of streaming. **Solution:** Check that `jq` is installed: ```bash theme={null} which jq ``` If not found: ```bash theme={null} brew install jq # macOS sudo apt install jq # Linux ``` ### Wrong Content in File **Problem:** Redirected file contains narration instead of just the report. **Solution:** Make sure your prompt ends with a clear content marker: ```markdown theme={null} #!/usr/bin/env -S ai --live --skip Explore the repo. Print findings as you go. Finally, generate a report in markdown format: # Report Title ... ``` The `#` heading tells AIRun where content starts. ## Next Steps Add --live to test scripts Use live output in CI/CD pipelines Stream processing for large datasets Complete guide to streaming output # Stdin Processing Source: https://docs.airun.me/examples/stdin-processing Pipe data into AIRun scripts for Unix-style automation Pipe data directly into AI scripts for analysis and transformation. This example shows how AIRun handles stdin like any Unix command. ## The Script ```markdown theme={null} #!/usr/bin/env -S ai --haiku Analyze the data provided on stdin. Summarize the key points, highlight anything unusual, and suggest next steps. ``` From `examples/analyze-stdin.md`. Uses Haiku for fast, cheap data analysis. ## How It Works ### Stdin Support AIRun scripts accept stdin like any Unix command: ```bash theme={null} cat data.json | ./analyze-stdin.md ``` The piped data is automatically prepended to your prompt: ``` [Data from stdin] {"users": 1500, "revenue": 45000, ...} Analyze the data provided on stdin. Summarize the key points... ``` ### Why Use Haiku? This script uses `--haiku` because: * **Fast** - Data analysis doesn't need deep reasoning * **Cheap** - Processing lots of files costs less * **Sufficient** - Haiku can summarize and identify patterns **Model selection for data tasks:** | Task | Model | | ------------------------------- | ---------- | | Summarize JSON/CSV/logs | `--haiku` | | Complex data transformations | `--sonnet` | | Data modeling and schema design | `--opus` | ## Running the Script ### Pipe from File ```bash theme={null} cat data.json | ./analyze-stdin.md ``` ### Pipe from Command ```bash theme={null} # Analyze git history git log --oneline -20 | ./analyze-stdin.md # Analyze package dependencies npm list --depth=0 | ./analyze-stdin.md # Analyze recent logs tail -100 /var/log/app.log | ./analyze-stdin.md ``` ### Pipe from API ```bash theme={null} # Fetch and analyze curl -s https://api.example.com/metrics | ./analyze-stdin.md # GitHub API curl -s https://api.github.com/repos/user/repo/issues | ./analyze-stdin.md ``` ### Save Output ```bash theme={null} cat data.json | ./analyze-stdin.md > analysis.txt ``` ## Real-World Usage ### Process JSON Data ```bash theme={null} cat metrics.json | ./analyze-stdin.md ``` **Input (metrics.json):** ```json theme={null} { "date": "2026-03-03", "users": 1500, "revenue": 45000, "signups": 120, "churn": 8, "response_time_ms": [120, 150, 890, 130, 125] } ``` **Output:** ``` Key metrics summary: - Strong user base: 1,500 active users - Revenue: $45,000 - Growth: 120 new signups, 8 churn (93% retention) Unusual findings: - Response time spike: 890ms outlier (others 120-150ms) - Investigate slow requests Next steps: - Monitor response times for performance regression - Analyze churn reasons - Maintain current signup momentum ``` ### Analyze CSV Files ```bash theme={null} cat sales.csv | ./analyze-stdin.md ``` **Input (sales.csv):** ```csv theme={null} date,product,quantity,revenue 2026-03-01,Widget A,50,5000 2026-03-01,Widget B,30,4500 2026-03-02,Widget A,45,4500 2026-03-02,Widget B,35,5250 2026-03-03,Widget A,0,0 ``` **Output:** ``` Sales analysis: - Widget B trending up (30 → 35 units, $4,500 → $5,250) - Widget A trending down (50 → 45 → 0 units) Unusual finding: - Widget A had ZERO sales on 2026-03-03 (out of stock?) Next steps: - Check Widget A inventory status immediately - Increase Widget B stock to meet demand ``` ### Process Log Files ```bash theme={null} tail -500 /var/log/nginx/access.log | ./analyze-stdin.md ``` With a custom prompt: ```markdown theme={null} #!/usr/bin/env -S ai --haiku Analyze the nginx access logs provided on stdin: - Request volume and patterns - Most accessed endpoints - Error rates - Unusual activity or potential attacks ``` ### Analyze Git History ```bash theme={null} git log --oneline -50 | ./analyze-stdin.md ``` Custom prompt: ```markdown theme={null} #!/usr/bin/env -S ai --haiku Analyze the git commit history on stdin: - What areas of the codebase are most active? - Are commit messages clear and descriptive? - Any patterns or concerns? ``` ## Chaining Scripts Together Pipe output from one AI script to another: ```bash theme={null} # Extract → Analyze → Format pipeline ./extract-data.md | ./analyze-stdin.md | ./format-report.md > final.txt ``` **extract-data.md:** ```markdown theme={null} #!/usr/bin/env -S ai --haiku --skip Read metrics.json and output only the fields: users, revenue, signups. Format as CSV. ``` **analyze-stdin.md:** ```markdown theme={null} #!/usr/bin/env -S ai --haiku Analyze the CSV data on stdin. Identify trends and anomalies. ``` **format-report.md:** ```markdown theme={null} #!/usr/bin/env -S ai --haiku Format the analysis on stdin as a professional email to executives. ``` ### Process Multiple Files ```bash theme={null} for file in logs/*.log; do echo "\n=== $file ===" cat "$file" | ./analyze-stdin.md done > analysis-report.txt ``` ## Controlling Stdin Position By default, piped data is **prepended** to your prompt. You can control this: ```bash theme={null} # Prepend (default) cat data.json | ./script.md # Append cat data.json | ./script.md --stdin-position append # Replace entire prompt cat data.json | ./script.md --stdin-position replace ``` **Example use case for append:** ```markdown theme={null} #!/usr/bin/env -S ai --haiku Analyze the following data and compare it to yesterday's metrics: ``` ```bash theme={null} cat today.json | ./compare.md --stdin-position append ``` Result: ``` Analyze the following data and compare it to yesterday's metrics: {"users": 1500, "revenue": 45000} ``` ## Data Processing Patterns ### Transform JSON to CSV ```markdown theme={null} #!/usr/bin/env -S ai --haiku Convert the JSON data on stdin to CSV format. Include all fields as columns. ``` ```bash theme={null} cat data.json | ./json-to-csv.md > data.csv ``` ### Filter and Aggregate ```markdown theme={null} #!/usr/bin/env -S ai --haiku The stdin contains JSON with an array of transactions. Filter for transactions > $1000 and sum the total. Output only the total amount. ``` ```bash theme={null} cat transactions.json | ./filter-sum.md # Output: $45,230 ``` ### Detect Anomalies ```markdown theme={null} #!/usr/bin/env -S ai --haiku Analyze the time-series data on stdin (CSV format). Detect anomalies using the 3-sigma rule. Output only the anomalous rows. ``` ```bash theme={null} cat timeseries.csv | ./detect-anomalies.md > anomalies.csv ``` ### Enrich Data ```markdown theme={null} #!/usr/bin/env -S ai --haiku The stdin contains a list of GitHub usernames (one per line). For each user, output: username, estimated location, primary language. Base this on common patterns in usernames and your knowledge. ``` ```bash theme={null} cat users.txt | ./enrich-users.md > enriched-users.csv ``` ## Stdin vs File Arguments ### When to Use Stdin ✅ **Use stdin when:** * Piping from commands (`git log | ./script.md`) * Chaining scripts together * Processing streams * Keeping scripts generic (don't hardcode filenames) ### When to Use File Arguments ✅ **Use file arguments when:** * The script needs to read multiple files * The script needs to know the filename * You want to be explicit about what's being processed **Example with file argument:** ```markdown theme={null} #!/usr/bin/env -S ai --haiku --skip Read metrics.json and analyze the data. Compare to historical data in metrics-history.json. ``` ```bash theme={null} ai script.md # Script reads files directly ``` Vs stdin approach: ```bash theme={null} cat metrics.json | ./script.md # Piped data ``` ## Combining Stdin with Other Flags ### Stdin + Live Output ```bash theme={null} cat large-dataset.csv | ai --live --haiku << 'EOF' Analyze the CSV data on stdin. Print a summary after every 1000 rows. Finally, output overall statistics. EOF ``` ### Stdin + Provider Override ```bash theme={null} # Script uses --haiku, override to --sonnet for better analysis cat complex-data.json | ai --sonnet analyze-stdin.md ``` ### Stdin + Variables ```markdown theme={null} #!/usr/bin/env -S ai --haiku --- vars: format: "summary" --- Analyze the data on stdin. Output format: {{format}} ``` ```bash theme={null} cat data.json | ./analyze.md --format "detailed report" ``` ## CI/CD Examples ### GitHub Actions ```yaml theme={null} name: Analyze Metrics on: schedule: - cron: '0 0 * * *' # Daily jobs: analyze: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup AIRun run: | curl -fsSL https://claude.ai/install.sh | bash git clone https://github.com/andisearch/airun.git cd airun && ./setup.sh - name: Fetch and analyze metrics run: | curl -s https://api.example.com/metrics | \ ai --apikey --haiku << 'EOF' > analysis.md Analyze the metrics JSON on stdin. Highlight any unusual trends or concerns. EOF env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - name: Upload analysis uses: actions/upload-artifact@v3 with: name: daily-analysis path: analysis.md ``` ### Process Database Dumps ```bash theme={null} #!/bin/bash # daily-db-analysis.sh # Export database metrics psql -c "SELECT * FROM daily_metrics WHERE date = CURRENT_DATE" -t -A -F"," | \ ai --haiku --apikey << 'EOF' > db-analysis.txt Analyze the database metrics CSV on stdin. Compare to typical patterns and flag anomalies. EOF # Email results mail -s "Daily DB Analysis" team@example.com < db-analysis.txt ``` ## Troubleshooting ### No Stdin Detected **Problem:** Script doesn't see piped data. **Solution:** Make sure you're actually piping: ```bash theme={null} # Wrong - passes filename as argument, not stdin ./analyze-stdin.md data.json # Correct - pipes file contents to stdin cat data.json | ./analyze-stdin.md ``` ### Stdin Data Not in Prompt **Problem:** AI says "no data provided." **Solution:** Check that stdin isn't empty: ```bash theme={null} # Debug: see what's being piped cat data.json | tee /dev/stderr | ./analyze-stdin.md ``` ### Binary Data Issues **Problem:** Piping binary files causes errors. **Solution:** AIRun expects text data. Convert binary first: ```bash theme={null} # Don't pipe binary directly cat image.png | ./analyze.md # ERROR # Convert to base64 first base64 image.png | ./analyze-base64.md # OK ``` ## Next Steps Complete data pipeline patterns Build multi-stage pipelines Automate data analysis in CI/CD Stream processing for large datasets # Test Automation Source: https://docs.airun.me/examples/test-automation Run test suites automatically and get intelligent analysis of failures Automate test execution and failure analysis. This example shows how to use `--skip` to run commands and report results. ## The Script ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip Run the test suite for this project. Report which tests passed and which failed. If any tests fail, explain the root cause. ``` From `examples/run-tests.md`. The AI detects your test framework automatically. ## How It Works ### Running Commands: `--skip` ```bash theme={null} --skip ``` Shorthand for `--dangerously-skip-permissions`. This allows the AI to: * **Run shell commands** (npm test, pytest, cargo test, etc.) * **Read test output** without prompting * **Analyze failures** by reading source files Without `--skip`, the AI would prompt you for permission before each command. `--skip` gives full system access. Only use it for: * **Trusted scripts** you wrote yourself * **Trusted directories** you control * **CI/CD environments** with proper sandboxing For granular control, use `--allowedTools` instead: ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --allowedTools 'Bash(npm test)' 'Read' Run the test suite. Report results but do not modify files. ``` ### Automatic Framework Detection The AI automatically detects your test framework: * **JavaScript/TypeScript:** npm test, jest, vitest, mocha * **Python:** pytest, unittest * **Rust:** cargo test * **Go:** go test * **Ruby:** rspec, minitest * **Shell scripts** in test/ directories It looks at package.json, Cargo.toml, go.mod, etc. to figure out what to run. ### Intelligent Failure Analysis When tests fail, the AI: 1. **Reads the error output** to understand what went wrong 2. **Examines source files** to find the root cause 3. **Explains the issue** in plain English 4. **Suggests fixes** (but doesn't apply them unless prompted) ## Running the Script ### Basic Usage ```bash theme={null} # Make it executable chmod +x run-tests.md # Run in any project directory cd ~/projects/my-app ./run-tests.md ``` Output: ``` [AI Runner] Using: Claude Code + Claude Pro [AI Runner] Model: Sonnet 4.6 I'll run the test suite using npm test. ✓ 45 tests passed ✗ 3 tests failed: 1. UserService.createUser - validation error File: src/services/user.service.test.ts:42 Root cause: Missing email validation in createUser function The test expects validation but the implementation skips it 2. API /auth/login - 500 error File: src/api/auth.test.ts:78 Root cause: Database connection not mocked in test setup The test tries to connect to a real database 3. Utils.parseDate - timezone handling File: src/utils/date.test.ts:91 Root cause: Date parsing assumes UTC but test runs in local timezone ``` ### Save Report to File ```bash theme={null} ./run-tests.md > test-report.txt ``` Only the AI's analysis is saved (status messages go to stderr). ### Override Model or Provider ```bash theme={null} # Use Haiku for faster/cheaper analysis ai --haiku run-tests.md # Use AWS Bedrock ai --aws --sonnet run-tests.md # Use local Ollama (free!) ai --ollama run-tests.md ``` ## Real-World Usage ### Pre-Commit Hook Run tests before each commit: ```bash theme={null} # .git/hooks/pre-commit #!/bin/bash echo "Running test suite..." if ! ai --haiku --skip << 'EOF' > /tmp/test-results.txt; then Run the test suite. Only output PASS or FAIL and a count. EOF cat /tmp/test-results.txt echo "Tests failed. Commit aborted." exit 1 fi echo "All tests passed." ``` ### CI/CD Integration **GitHub Actions:** ```yaml theme={null} # .github/workflows/test.yml name: Test with AI Analysis on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Node uses: actions/setup-node@v3 with: node-version: '20' - name: Install AIRun run: | curl -fsSL https://claude.ai/install.sh | bash git clone https://github.com/andisearch/airun.git cd airun && ./setup.sh - name: Run tests with AI analysis run: | ai --apikey --sonnet --skip << 'EOF' > test-report.md Run the test suite. Report pass/fail counts. If any tests fail, analyze root causes and suggest fixes. EOF env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - name: Upload report uses: actions/upload-artifact@v3 with: name: test-analysis path: test-report.md ``` **GitLab CI:** ```yaml theme={null} # .gitlab-ci.yml test: stage: test image: node:20 script: - curl -fsSL https://claude.ai/install.sh | bash - git clone https://github.com/andisearch/airun.git - cd airun && ./setup.sh && cd .. - | ai --apikey --sonnet --skip << 'EOF' > test-report.md Run the test suite. Report pass/fail counts and analyze failures. EOF artifacts: paths: - test-report.md variables: ANTHROPIC_API_KEY: $ANTHROPIC_API_KEY ``` ### Nightly Test Analysis Run comprehensive test analysis overnight: ```bash theme={null} #!/bin/bash # nightly-test-analysis.sh cd ~/projects/my-app ai --apikey --opus --skip << 'EOF' > "test-report-$(date +%Y-%m-%d).md" Run the full test suite including integration tests. For each failure: 1. Identify the root cause 2. Check git history for recent changes to related files 3. Suggest specific fixes with code snippets 4. Rate the severity (critical/high/medium/low) Summarize test health trends if you can access previous reports. EOF # Email the report mail -s "Nightly Test Report" dev-team@company.com < "test-report-$(date +%Y-%m-%d).md" ``` ### Fix Tests Automatically This modifies code. Only use in development, never in CI without review. ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip Run the test suite. If any tests fail: 1. Analyze the root cause 2. Fix the issue in the source code 3. Run tests again to verify the fix 4. Report what you changed Do NOT commit changes. Just fix and verify. ``` ## Customizing the Analysis ### Focus on Specific Test Types **Unit tests only:** ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip Run only unit tests (npm run test:unit). Report pass/fail counts and analyze failures. ``` **Integration tests with setup:** ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip Run integration tests: 1. Start docker-compose services 2. Wait for services to be healthy 3. Run npm run test:integration 4. Stop services when done Analyze any failures. ``` ### Performance Testing ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip Run performance tests: 1. Execute npm run test:perf 2. Compare results to previous baseline in perf-baseline.json 3. Flag any regressions >10% 4. Identify the slowest tests ``` ### Coverage Analysis ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip Run tests with coverage: 1. Execute npm run test:coverage 2. Report overall coverage percentage 3. List files with <80% coverage 4. Suggest priority areas for new tests ``` ## Combining with Live Output For long test suites, add `--live` to see progress: ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --skip --live Run the test suite. Print a status update after each test file completes. Finally, report pass/fail counts and analyze failures. ``` Now you'll see updates as tests run instead of waiting for everything to complete. ## Security Best Practices ### Use Granular Permissions Instead of `--skip`, specify exactly what's allowed: ```markdown theme={null} #!/usr/bin/env -S ai --sonnet --allowedTools 'Bash(npm test)' 'Read' Run the test suite. Report results but do not modify any files. ``` This prevents accidental modifications even if your prompt changes. ### CI/CD Sandboxing In CI/CD, run inside containers: ```yaml theme={null} test: image: node:20 script: - ai --skip test-script.md ``` If the AI does something unexpected, it only affects the container. ### Limit Test Commands ```bash theme={null} --allowedTools 'Bash(npm test)' 'Bash(pytest)' 'Read' ``` Explicitly list which test commands are allowed. ## Next Steps See test progress in real-time Complete CI/CD integration patterns Automated code review workflows Security best practices for automation # CI/CD & Automation Source: https://docs.airun.me/guides/automation Run AI scripts in continuous integration pipelines with proper permissions and error handling ## Overview Andi AIRun scripts are perfect for CI/CD workflows: automated testing, code review, documentation generation, and more. This guide covers how to run scripts reliably in automation environments. ## Running Scripts in CI/CD ### Basic CI Script ```markdown theme={null} #!/usr/bin/env -S ai --apikey --haiku --skip Run the linter and fix any issues. Then run the test suite. Commit fixes with a descriptive message if all tests pass. ``` Key flags for CI: * `--apikey` — Use API key authentication (set `ANTHROPIC_API_KEY` environment variable) * `--haiku` — Fast, cost-effective model for routine tasks * `--skip` — No permission prompts (required for unattended execution) ### GitHub Actions Example ```yaml .github/workflows/ai-review.yml theme={null} name: AI Code Review on: [pull_request] jobs: review: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install Andi AIRun run: | curl -fsSL https://andi.ai/install.sh | sh echo "$HOME/.andi/bin" >> $GITHUB_PATH - name: Run AI Review env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} run: | chmod +x ./scripts/review.md ./scripts/review.md > review-report.md - name: Post Review Comment uses: actions/github-script@v7 with: script: | const fs = require('fs'); const report = fs.readFileSync('review-report.md', 'utf8'); github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: report }); ``` ### GitLab CI Example ```yaml .gitlab-ci.yml theme={null} ai-tests: stage: test image: ubuntu:latest before_script: - curl -fsSL https://andi.ai/install.sh | sh - export PATH="$HOME/.andi/bin:$PATH" script: - chmod +x ./scripts/run-tests.md - ./scripts/run-tests.md variables: ANTHROPIC_API_KEY: $ANTHROPIC_API_KEY artifacts: reports: junit: test-results.xml ``` ## Permission Flags for Automation ### The `--skip` Shortcut For quick automation, use `--skip` (shorthand for `--dangerously-skip-permissions`): ```markdown theme={null} #!/usr/bin/env -S ai --skip Run the test suite and fix any failing tests. ``` ### The `--bypass` Alternative Use `--bypass` (shorthand for `--permission-mode bypassPermissions`) when you need composability with other permission settings: ```markdown theme={null} #!/usr/bin/env -S ai --bypass Run the test suite and fix any failing tests. ``` ### Granular Tool Access For better security, restrict to specific tools with `--allowedTools`: ```markdown theme={null} #!/usr/bin/env -S ai --allowedTools 'Bash(npm test)' 'Bash(npm run build)' 'Read' Run tests and build. Report results but do not modify any files. ``` ### Permission Flag Precedence `ai` resolves permission shortcuts before passing flags to Claude Code. When conflicts are detected, explicit flags take precedence: * `--permission-mode ` and `--dangerously-skip-permissions` are **explicit** — they always win * `--skip` and `--bypass` are **shortcuts** — ignored with a warning if an explicit flag is also present * **CLI flags override shebang flags** — if you run `ai --permission-mode plan script.md` and the script has `--skip` in its shebang, plan mode is used | You use | What happens | | ----------------------------------------------------------- | ----------------------------------------------------------------------------------- | | `ai --skip` | Same as `--dangerously-skip-permissions` (nuclear — overrides all permission modes) | | `ai --bypass` | Same as `--permission-mode bypassPermissions` (mode-based — composable) | | `ai --skip --permission-mode plan` | Plan mode used, `--skip` ignored (warning shown) | | `ai --bypass --permission-mode plan` | Plan mode used, `--bypass` ignored (warning shown) | | `ai --permission-mode plan script.md` (script has `--skip`) | Plan mode used, shebang `--skip` ignored | ## Exit Codes and Error Handling ### Exit Codes Andi AIRun returns standard Unix exit codes: * `0` — Success * `1` — General error (AI task failed, tool error, etc.) * `2` — Invalid arguments or configuration ### Handling Failures in Scripts Use standard shell error handling: ```bash theme={null} #!/bin/bash set -e # Exit on error ./test-runner.md || { echo "Tests failed" exit 1 } ./deploy.md echo "Deployment successful" ``` ### Conditional Execution ```bash theme={null} if ./security-scan.md; then echo "Security scan passed" ./deploy.md else echo "Security issues found, deployment blocked" exit 1 fi ``` ### Retry Logic ```bash theme={null} #!/bin/bash max_retries=3 attempt=0 while [ $attempt -lt $max_retries ]; do if ./flaky-test.md; then echo "Tests passed" exit 0 fi attempt=$((attempt + 1)) echo "Attempt $attempt failed, retrying..." sleep 5 done echo "All retries failed" exit 1 ``` ## Real-World Examples ### Example 1: Automated Test Runner ```markdown run-tests.md theme={null} #!/usr/bin/env -S ai --sonnet --skip Run the test suite for this project. Report which tests passed and which failed. If any tests fail, explain the root cause. ``` Usage in CI: ```bash theme={null} ./run-tests.md > test-report.md ``` ### Example 2: Documentation Generator ```markdown generate-docs.md theme={null} #!/usr/bin/env -S ai --skip Read the source files in `src/` and generate an `ARCHITECTURE.md` file documenting the codebase structure, key modules, and data flow. ``` Usage in CI: ```yaml theme={null} - name: Generate docs run: ./generate-docs.md - name: Commit docs run: | git config user.name "AI Bot" git config user.email "bot@example.com" git add ARCHITECTURE.md git commit -m "Update architecture docs" || true git push ``` ### Example 3: Security Audit ```markdown security-audit.md theme={null} #!/usr/bin/env -S ai --aws --opus Review the code in this repository for security vulnerabilities. Focus on OWASP Top 10 issues. Be specific about file and line numbers. Output findings in markdown format with severity levels. ``` Usage in CI: ```bash theme={null} ./security-audit.md > security-report.md if grep -q "CRITICAL\|HIGH" security-report.md; then echo "High-severity issues found" exit 1 fi ``` ### Example 4: PR Description Generator ```markdown pr-description.md theme={null} #!/usr/bin/env -S ai --haiku Analyze the git diff and recent commits. Generate a concise PR description that explains what changed, why, and any breaking changes or migration steps. ``` Usage: ```bash theme={null} git diff main...HEAD | ./pr-description.md > pr-body.md gh pr create --title "Feature: New API" --body-file pr-body.md ``` ## Flag Precedence `ai` resolves flags from multiple sources. Higher sources override lower ones: \| Priority | Source | Example | \|----------|--------|---------|| \| 1 (highest) | CLI flags | `ai --aws --opus script.md` | \| 2 | Shebang flags | `#!/usr/bin/env -S ai --ollama --low` | \| 3 | Saved defaults | `ai --aws --opus --set-default` | \| 4 (lowest) | Auto-detection | Current Claude subscription | **Example:** A script has `#!/usr/bin/env -S ai --ollama --low`. Running `ai script.md` uses Ollama (shebang). Running `ai --aws script.md` uses AWS (CLI overrides shebang). ## Passing Claude Code Flags Any flag not recognized by `ai` is passed directly to Claude Code. Useful flags for automation: \| Flag | Purpose | Example | \|------|---------|---------|| \| `--skip` | Shortcut for `--dangerously-skip-permissions` | Quick automation | \| `--bypass` | Shortcut for `--permission-mode bypassPermissions` | Quick automation | \| `--max-turns N` | Limit agentic loop iterations | Prevent runaway scripts | \| `--output-format stream-json` | Structured JSON output | Pipeline integration | \| `--live` | Stream text in real-time | Long-running scripts | Combine with `ai` flags freely: ```markdown theme={null} #!/usr/bin/env -S ai --aws --opus --skip --max-turns 10 ``` ## Security Best Practices **Always run AI automation in sandboxed environments:** 1. **Use containers** — Run scripts inside Docker containers with limited permissions 2. **Restrict file access** — Mount only necessary directories 3. **Network isolation** — Use network policies to limit outbound connections 4. **Secret management** — Never hardcode API keys; use environment variables or secret managers 5. **Code review** — Review AI-generated changes before merging 6. **Audit logs** — Log all AI actions for security monitoring ### Docker Example ```dockerfile theme={null} FROM ubuntu:latest RUN curl -fsSL https://andi.ai/install.sh | sh # Run as non-root user RUN useradd -m airunner USER airunner WORKDIR /workspace COPY --chown=airunner:airunner ./scripts /workspace/scripts ENTRYPOINT ["/home/airunner/.andi/bin/ai"] ``` Run it: ```bash theme={null} docker build -t ai-runner . docker run --rm \ -e ANTHROPIC_API_KEY \ -v $(pwd):/workspace:ro \ ai-runner --skip ./scripts/review.md ``` ## Next Steps Deep dive into permission modes and security Stream progress for long-running CI jobs Make scripts reusable with CLI overrides Learn script basics and common patterns # Live Output & Streaming Source: https://docs.airun.me/guides/live-output Stream AI progress in real-time for long-running scripts and browser automation ## Overview By default, AI scripts wait for the full response before printing anything. The `--live` flag enables real-time streaming, showing progress as the AI works. This is essential for long-running scripts where you want immediate feedback. ## How `--live` Works ### Turn-Level Streaming `--live` streams at **turn granularity** — each time Claude writes a text response between tool calls, that text appears immediately. This means your prompt needs to tell Claude to narrate its progress, otherwise it may silently use tools and only output text at the end. ### Example: With Progress Narration ```markdown explore.md theme={null} #!/usr/bin/env -S ai --skip --live Explore this repository. Print a brief summary after examining each directory. Finally, generate a concise report in markdown format. ``` Run it: ```bash theme={null} ./explore.md ``` Output streams incrementally: ``` [AI Runner] Using: Claude Code + Claude Pro [AI Runner] Model: (system default) Let me explore the repository structure... I've examined the src/ directory. It contains the core application logic with modules for authentication, data processing, and API handlers. Now checking the test/ directory... Tests are organized by feature with good coverage. Found 127 test files. Generating final report: # Repository Summary ... ``` ### Example: Without Progress Narration ```markdown explore-silent.md theme={null} #!/usr/bin/env -S ai --skip --live Explore this repository and write a summary. ``` Run it: ```bash theme={null} ./explore-silent.md ``` No intermediate output (Claude works silently): ``` [AI Runner] Using: Claude Code + Claude Pro [AI Runner] Model: (system default) [...long pause...] # Repository Summary ... ``` Both produce the same final result, but only the first streams progress. The key is phrases like: * **"print as you go"** * **"step by step"** * **"describe what you find"** * **"narrate your progress"** * **"summarize after each step"** These prompt Claude to write text between tool calls, giving `--live` something to stream. ## Output Redirection When stdout is redirected to a file, `--live` automatically separates narration from content: ```bash theme={null} ./live-report.md > report.md ``` **Console (stderr):** ``` [AI Runner] Using: Claude Code + Claude Pro [AI Runner] Model: (system default) I'll explore the repository structure and key files... Now let me look at the core scripts and provider structure. Here's my report: [AI Runner] Done (70 lines written) ``` **File (stdout):** ```markdown theme={null} # Repository Summary This repository contains... ## Key Features ... ``` ### How It Works 1. **Intermediate turns** (narration, progress) stream to stderr in real-time 2. **The last turn** is split at the first content marker: * YAML frontmatter `---` * Markdown heading `#` 3. **Preamble text** before the marker goes to stderr 4. **Content** from the marker onward goes to the file (stdout) 5. **Summary message** "Done (N lines written)" appears on stderr when complete This means you can watch progress on the console while capturing clean output in a file. ### Example: Generate Documentation ```markdown generate-docs.md theme={null} #!/usr/bin/env -S ai --sonnet --skip --live Explore this repository and write a short summary of what it does, its key features, and how to get started. Print your findings as you go. Finally, generate a concise report in markdown format. ``` Run it: ```bash theme={null} ./generate-docs.md > ARCHITECTURE.md ``` You see progress on console: ``` Examining the source structure... Found 15 modules in src/ Analyzing dependencies... Generating final report: [AI Runner] Done (82 lines written) ``` While `ARCHITECTURE.md` contains only the clean report. ## When to Use `--live` Use `--live` for: * **Long-running scripts** (>30 seconds) * **Browser automation** with Chrome * **Multi-step workflows** where you want to see each step * **CI/CD jobs** where you need progress visibility * **Debugging** to see what the AI is doing in real-time Skip `--live` for: * **Quick read-only queries** (under 10 seconds) * **Piped output** where you only care about the final result * **Silent automation** where you want minimal output ## Piped Content with Live Streaming You can combine stdin piping with `--live`: ```bash theme={null} cat data.json | ai --live --skip analyze.md ``` The AI reads from stdin and streams progress to stdout: ``` [AI Runner] Using: Claude Code + Claude Pro [AI Runner] Model: (system default) Analyzing the JSON data... Found 1,247 records spanning 2020-2024. Detected 3 outliers in the revenue column. Key findings: - Average revenue increased 23% year-over-year - Q4 2023 shows unusual spike (investigate further) ... ``` ## Browser Automation with Chrome `--live` pairs perfectly with `--chrome` (a Claude Code flag) for browser automation where steps take time and you need real-time progress: ```markdown test-login.md theme={null} #!/usr/bin/env -S ai --skip --chrome --live Navigate to https://app.example.com and verify the login flow works. Describe each step as you go: 1. Load the page 2. Fill in credentials 3. Click login 4. Verify dashboard appears ``` Run it: ```bash theme={null} ./test-login.md ``` Output streams in real-time: ``` [AI Runner] Using: Claude Code + Claude Pro [AI Runner] Model: (system default) Step 1: Loading https://app.example.com... Page loaded successfully. Login form is visible. Step 2: Filling in test credentials... Entered username and password. Step 3: Clicking login button... Submitting form... Redirecting... Step 4: Verifying dashboard... Dashboard loaded. User profile visible in header. Login flow verified successfully. ``` Without `--live`, you'd see nothing until the entire test completes (which could be minutes). ## Using `--quiet` to Suppress Live Output Override `--live` with `--quiet` when you want silent operation: ```bash theme={null} ai --quiet ./browser-test.md > report.md ``` This is useful in CI/CD where you only want the final result: * No progress narration * No \[AI Runner] status messages * Only the final output content ## Real-World Examples ### Example 1: Repository Exploration ```markdown explore-repo.md theme={null} #!/usr/bin/env -S ai --sonnet --skip --live Explore this repository and write a short summary of what it does, its key features, and how to get started. Print your findings as you go. Finally, generate a concise report in markdown format. ``` Usage: ```bash theme={null} ./explore-repo.md > README.md ``` ### Example 2: Test Suite Runner ```markdown run-tests.md theme={null} #!/usr/bin/env -S ai --sonnet --skip --live Run the test suite for this project. After each test file completes, report the results. Finally, summarize: how many passed/failed. ``` Usage: ```bash theme={null} ./run-tests.md ``` ### Example 3: Data Analysis Pipeline ```markdown analyze-pipeline.md theme={null} #!/usr/bin/env -S ai --haiku --skip --live Process the data through these steps: 1. Load and validate the input 2. Clean and normalize values 3. Calculate summary statistics 4. Identify outliers Print progress after each step. Output final results in JSON format. ``` Usage: ```bash theme={null} cat raw-data.csv | ./analyze-pipeline.md > results.json ``` ### Example 4: Security Scan ```markdown security-scan.md theme={null} #!/usr/bin/env -S ai --opus --skip --live Scan this codebase for security vulnerabilities. Check each directory and report findings as you go. Focus on: - SQL injection risks - XSS vulnerabilities - Insecure dependencies Finally, generate a security report with severity levels. ``` Usage: ```bash theme={null} ./security-scan.md > security-report.md ``` ## Requirements `--live` requires `jq` to be installed: ```bash theme={null} # macOS brew install jq # Ubuntu/Debian sudo apt-get install jq # CentOS/RHEL sudo yum install jq ``` ## Troubleshooting ### No Intermediate Output **Problem:** `--live` flag is set but nothing streams until the end **Solution:** Add progress narration to your prompt: ```markdown theme={null} # Before Explore the repository and write a summary. # After Explore the repository. Print findings after examining each directory. Finally, write a summary. ``` ### Output Goes to Wrong Stream **Problem:** Progress text ends up in the output file **Solution:** Ensure your final output starts with a content marker (`#` heading or `---` frontmatter). The system splits at the first marker. ### `jq` Not Found Error **Problem:** `[AI Runner] Error: jq not found` **Solution:** Install `jq`: ```bash theme={null} brew install jq # macOS sudo apt-get install jq # Linux ``` ## Best Practices **Do:** * Add `--live` to any script that takes >30 seconds * Prompt the AI to narrate progress ("print as you go") * Start final output with `#` heading for clean file redirection * Use `--live` with `--chrome` for browser automation * Override with `--quiet` in CI when you want silent operation **Don't:** * Rely on `--live` for scripts that work silently (add narration prompts) * Forget to install `jq` before using `--live` * Mix `--live` narration with structured output (use separate turns) ## Next Steps Use live output in continuous integration pipelines Learn script basics and common patterns Make scripts reusable with CLI overrides Control what scripts can do # Permission System Source: https://docs.airun.me/guides/permissions Control what AI scripts can do with granular permission modes and security best practices ## Overview Andi AIRun's permission system controls what actions AI scripts can take. By default, scripts run in read-only mode. For scripts that need to write files, run commands, or take actions, you must explicitly grant permissions. ## Permission Modes ### Default Mode (Read-Only) No permission flags needed. The AI can: * Read files and directories * Analyze code * Search and grep * Output text The AI cannot: * Write or modify files * Run shell commands * Make network requests * Install packages **Example:** ```markdown theme={null} #!/usr/bin/env ai Analyze this codebase and summarize the architecture. ``` ### Bypass Mode (`--bypass`) Shortcut for `--permission-mode bypassPermissions`. Grants full access through the permission mode system. Composable with other Claude Code settings. **When to use:** Standard automation where you need full access and may want to compose with other permission settings. **Example:** ```markdown theme={null} #!/usr/bin/env -S ai --bypass Run the test suite and fix any failing tests. ``` **What it enables:** * Full file system access (read, write, delete) * Shell command execution * Network requests * Package installation * All Claude Code tools ### Skip Permissions (`--skip`) Shortcut for `--dangerously-skip-permissions`. Nuclear option that bypasses ALL permission checks and overrides any `--permission-mode` setting. **When to use:** Quick, simple automation where you need absolute full access. **Example:** ```markdown theme={null} #!/usr/bin/env -S ai --skip Run the test suite and fix any failing tests. ``` **What it enables:** * Everything `--bypass` enables * Overrides any other permission mode flags * Most aggressive permission setting ### Allowed Tools (`--allowedTools`) Granular control — only specified tools are allowed. Best for security-conscious automation. **When to use:** When you want to restrict the AI to specific, approved operations. **Example:** ```markdown theme={null} #!/usr/bin/env -S ai --allowedTools 'Bash(npm test)' 'Bash(npm run lint)' 'Read' Run tests and linting. Report results but do not modify any files. ``` **Syntax:** * `'Read'` — Allow reading files * `'Write'` — Allow writing files * `'Bash(command)'` — Allow specific shell command * `'Bash'` — Allow all shell commands (not recommended) **Multiple tools:** ```bash theme={null} --allowedTools 'Bash(npm test)' 'Bash(git status)' 'Read' 'Write' ``` ## `--skip` vs `--bypass` Difference Both shortcuts result in no permission prompts, but they work differently internally: ### `--skip` (Nuclear Option) * Expands to `--dangerously-skip-permissions` * Standalone flag that completely bypasses all permission checks * **Overrides** any `--permission-mode` setting (even if you set both) * Use for simple, quick automation ### `--bypass` (Composable) * Expands to `--permission-mode bypassPermissions` * Sets permission mode through the standard mode system * Respects the mode framework * Composable with other Claude Code settings * Use when working with advanced permission configurations ### Comparison Table | Feature | `--skip` | `--bypass` | | ----------------------------- | ------------- | --------------------- | | Full access | Yes | Yes | | Permission prompts | None | None | | Overrides `--permission-mode` | Yes | No | | Composable with modes | No | Yes | | Recommended for | Quick scripts | Production automation | ### When in Doubt For most automation scripts, either works. **Use `--bypass`** when you want future flexibility. ## Permission Flag Precedence When multiple permission flags are present, `ai` resolves them in order: ### Explicit Flags Always Win * `--permission-mode ` is **explicit** — always takes precedence * `--dangerously-skip-permissions` is **explicit** — always takes precedence * `--skip` and `--bypass` are **shortcuts** — ignored if explicit flags present ### CLI Overrides Shebang **CLI flags override shebang flags** — if you run `ai --permission-mode plan script.md` and the script has `--skip` in its shebang, plan mode is used. ### Examples | You use | What happens | | ------------------------------------- | ---------------------------------------------------------- | | `ai --skip` | Same as `--dangerously-skip-permissions` (nuclear) | | `ai --bypass` | Same as `--permission-mode bypassPermissions` (mode-based) | | `ai --skip --permission-mode plan` | Plan mode used, `--skip` ignored (warning shown) | | `ai --bypass --permission-mode plan` | Plan mode used, `--bypass` ignored (warning shown) | | `ai --permission-mode plan script.md` | Plan mode used, even if script has `--skip` | ### Conflict Resolution ```markdown script.md theme={null} #!/usr/bin/env -S ai --skip Do something ``` Run with override: ```bash theme={null} ai --permission-mode plan script.md ``` Result: ``` [AI Runner] Warning: Ignoring --skip shortcut (--permission-mode plan takes precedence) [AI Runner] Using permission mode: plan ``` ## Granular Control with `--allowedTools` ### Tool Syntax **Read-only tools:** ```bash theme={null} --allowedTools 'Read' 'Glob' 'Grep' ``` **Specific shell commands:** ```bash theme={null} --allowedTools 'Bash(npm test)' 'Bash(git status)' ``` **File operations:** ```bash theme={null} --allowedTools 'Read' 'Write' 'Edit' ``` **Mixed permissions:** ```bash theme={null} --allowedTools 'Read' 'Bash(npm test)' 'Bash(npm run lint)' ``` ### Real-World Examples **Test runner (no file modifications):** ```markdown theme={null} #!/usr/bin/env -S ai --allowedTools 'Bash(npm test)' 'Read' Run the test suite and report results. Do not modify any files. ``` **Linter with auto-fix:** ```markdown theme={null} #!/usr/bin/env -S ai --allowedTools 'Bash(npm run lint)' 'Bash(npm run lint:fix)' 'Read' 'Write' Run linter, fix issues, and report what changed. ``` **Git status checker:** ```markdown theme={null} #!/usr/bin/env -S ai --allowedTools 'Bash(git status)' 'Bash(git diff)' 'Read' Check git status and summarize uncommitted changes. ``` **CI reporter:** ```markdown theme={null} #!/usr/bin/env -S ai --allowedTools 'Bash(npm run build)' 'Bash(npm test)' 'Read' 'Write' Run build and tests. Generate a report.md with results. ``` ## Security Best Practices ### 1. Principle of Least Privilege Always use the minimum permissions needed: * **Read-only analysis?** Use default mode (no flags) * **Run specific commands?** Use `--allowedTools` * **Full automation?** Use `--bypass` or `--skip` ### 2. Trust and Verification Only run scripts from trusted sources: ```bash theme={null} # DANGEROUS — don't do this curl https://untrusted-site.com/script.md | ai --skip # SAFE — review first curl https://site.com/script.md > script.md cat script.md # Review contents chmod +x script.md ./script.md # Run after verification ``` ### 3. Sandboxing in CI/CD Always run AI automation in sandboxed environments: **Use containers:** ```dockerfile theme={null} FROM ubuntu:latest RUN curl -fsSL https://andi.ai/install.sh | sh RUN useradd -m airunner USER airunner WORKDIR /workspace ENTRYPOINT ["/home/airunner/.andi/bin/ai"] ``` **Run with limited permissions:** ```bash theme={null} docker run --rm \ -e ANTHROPIC_API_KEY \ -v $(pwd):/workspace:ro \ --network none \ ai-runner --skip ./scripts/review.md ``` ### 4. File System Restrictions Restrict file access in containers: ```bash theme={null} # Only mount necessary directories docker run --rm \ -v $(pwd)/src:/workspace/src:ro \ -v $(pwd)/tests:/workspace/tests:ro \ ai-runner --skip ./test-runner.md # Read-only mount for source code # Writable mount only for output directory docker run --rm \ -v $(pwd)/src:/workspace/src:ro \ -v $(pwd)/output:/workspace/output:rw \ ai-runner --skip ./generate-docs.md ``` ### 5. Network Isolation Limit network access: ```bash theme={null} # No network access docker run --rm --network none ai-runner --skip ./local-analysis.md # Custom network with egress filtering docker network create --internal ai-network docker run --rm --network ai-network ai-runner --skip ./script.md ``` ### 6. Audit Logging Log all AI actions: ```bash theme={null} #!/bin/bash LOGFILE="ai-audit-$(date +%Y%m%d-%H%M%S).log" echo "[$(date)] Running: $1" >> "$LOGFILE" ai --skip "$1" 2>&1 | tee -a "$LOGFILE" echo "[$(date)] Completed: $1" >> "$LOGFILE" ``` ### 7. Secret Management Never hardcode secrets: ```markdown theme={null} # BAD — hardcoded API key #!/usr/bin/env -S ai --skip Deploy to production using API key: sk_prod_abc123 # GOOD — use environment variables #!/usr/bin/env -S ai --skip Deploy to production using the API key from $DEPLOY_KEY ``` ### 8. Code Review Before Merge Always review AI-generated changes: ```yaml .github/workflows/ai-fix.yml theme={null} - name: Run AI fixer run: ./fix-issues.md - name: Show changes run: git diff - name: Create PR (not direct merge) run: | git checkout -b ai-fixes-${{ github.run_id }} git commit -am "AI: Fix issues" git push origin ai-fixes-${{ github.run_id }} gh pr create --title "AI: Fix issues" --body "Review before merging" ``` ## Permission Mode Reference ### Complete Mode Table | Mode | Shebang | Long Form | Short Form | Behavior | | ------------- | ---------------- | ------------------------------------- | ---------- | ------------------------ | | Default | *(none)* | — | — | Read-only | | Bypass | `--bypass` | `--permission-mode bypassPermissions` | `--bypass` | Full access (composable) | | Skip | `--skip` | `--dangerously-skip-permissions` | `--skip` | Full access (nuclear) | | Allowed Tools | `--allowedTools` | `--allowedTools 'Tool1' 'Tool2'` | — | Granular | | Plan | — | `--permission-mode plan` | — | Plan-only (no execution) | ### Available Tools for `--allowedTools` \| Tool | Purpose | Example | \|------|---------|---------|| \| `Read` | Read files | `--allowedTools 'Read'` | \| `Write` | Write files | `--allowedTools 'Write'` | \| `Edit` | Edit files | `--allowedTools 'Edit'` | \| `Bash` | All shell commands | `--allowedTools 'Bash'` (not recommended) | \| `Bash(cmd)` | Specific command | `--allowedTools 'Bash(npm test)'` | \| `Glob` | File pattern search | `--allowedTools 'Glob'` | \| `Grep` | Content search | `--allowedTools 'Grep'` | ## Common Patterns ### Pattern 1: Secure Test Runner ```markdown theme={null} #!/usr/bin/env -S ai --allowedTools 'Bash(npm test)' 'Bash(npm run coverage)' 'Read' Run tests with coverage. Report results. Do not modify code. ``` ### Pattern 2: Sandboxed CI Job ```yaml theme={null} - name: AI Code Review run: | docker run --rm \ --network none \ -v $(pwd):/workspace:ro \ -e ANTHROPIC_API_KEY \ ai-runner --bypass ./review.md ``` ### Pattern 3: Gradual Permission Escalation ```bash theme={null} # Start with read-only analysis ./analyze.md # If user approves, run with limited tools ai --allowedTools 'Bash(npm test)' 'Read' ./test-and-fix.md # If tests pass, run with full permissions ai --bypass ./deploy.md ``` ### Pattern 4: Multi-Stage Pipeline ```bash theme={null} # Stage 1: Analysis (read-only) ./analyze.md > analysis.md # Stage 2: Test (limited permissions) ai --allowedTools 'Bash(npm test)' 'Read' ./test.md > test-results.md # Stage 3: Fix (full permissions, but only if tests failed) if grep -q "FAILED" test-results.md; then ai --bypass ./fix-tests.md fi ``` ## Troubleshooting ### Permission Denied Errors **Problem:** Script tries to write file but fails with permission error **Solution:** Add appropriate permission flag: ```markdown theme={null} # Before #!/usr/bin/env ai # After #!/usr/bin/env -S ai --bypass ``` ### Tool Not Allowed **Problem:** `Error: Tool 'Bash' not allowed` **Solution:** Add tool to allowed list: ```markdown theme={null} # Before #!/usr/bin/env -S ai --allowedTools 'Read' # After #!/usr/bin/env -S ai --allowedTools 'Read' 'Bash(npm test)' ``` ### Conflicting Permission Flags **Problem:** Warning about ignored shortcuts **Solution:** Remove shortcut flags when using explicit modes: ```bash theme={null} # Before (conflict) ai --skip --permission-mode plan script.md # After (no conflict) ai --permission-mode plan script.md ``` ## Next Steps Learn script basics and common patterns Run scripts in CI/CD with proper security Stream progress in real-time Make scripts reusable with CLI overrides # Writing Scripts Source: https://docs.airun.me/guides/scripting Create executable markdown scripts that analyze code, run commands, and automate workflows ## Overview Andi AIRun scripts are executable markdown files that can read code, run commands, write files, and automate complex workflows. Scripts use a shebang to specify the AI model and permissions, then contain natural language instructions that the AI executes. ## Basic Script Structure A minimal script looks like this: ```markdown theme={null} #!/usr/bin/env ai Analyze this codebase and summarize the architecture. ``` Make it executable and run it: ```bash theme={null} chmod +x analyze.md ./analyze.md ``` ### The `-S` Flag (Essential for Shebangs) Standard `env` only passes a single argument. To pass flags to `ai` in a shebang, you need `env -S` (split string): ```markdown theme={null} #!/usr/bin/env ai # Works (no extra flags) #!/usr/bin/env -S ai --aws # Works (with -S) #!/usr/bin/env ai --aws # FAILS — env treats "ai --aws" as one command ``` `-S` tells `env` to split the string into separate arguments. **Use it whenever your shebang has flags.** ## Permission Modes By default, scripts run with limited permissions — they can read code but won't write files or run commands without approval. For scripts that need to take actions, set a permission mode. ### Available Modes | Mode | Shebang Flag | Shortcut | Behavior | | -------------------- | ----------------------------------------- | ---------- | ----------------------------------------------------------------------- | | **Default** | *(none)* | — | Read-only — can analyze code but won't modify anything | | **Bypass Mode** | `--permission-mode bypassPermissions` | `--bypass` | Full access via permission mode system — composable with other settings | | **Skip Permissions** | `--dangerously-skip-permissions` | `--skip` | Nuclear — bypasses ALL permission checks, overrides `--permission-mode` | | **Allowed Tools** | `--allowedTools 'Bash(npm test)' 'Write'` | — | Granular — only specified tools allowed | `--bypass` and `--skip` both result in no permission prompts, but `--skip` is more aggressive — it overrides any `--permission-mode` flag. Use `--bypass` when you may want to compose with other permission settings in the future. ### Examples **Read-only script** (no permission flags needed): ```markdown theme={null} #!/usr/bin/env ai Analyze this codebase and summarize the architecture. ``` **Full automation** (script needs to run commands and write files): ```markdown theme={null} #!/usr/bin/env -S ai --skip Run the test suite and fix any failing tests. ``` Or equivalently: `#!/usr/bin/env -S ai --bypass` **Granular permissions** (only allow specific tools): ```markdown theme={null} #!/usr/bin/env -S ai --allowedTools 'Bash(npm test)' 'Bash(npm run lint)' 'Read' Run tests and linting. Report results but do not modify any files. ``` ## Common Patterns ### Run Tests and Report Results ```markdown theme={null} #!/usr/bin/env -S ai --skip Run `./test/automation/run_tests.sh` and summarize: how many passed/failed. ``` ### Generate Documentation ```markdown theme={null} #!/usr/bin/env -S ai --skip Read the source files in `src/` and generate a `ARCHITECTURE.md` documenting the codebase structure. ``` ### Pipe Data In, Get Results Out ```bash theme={null} cat data.json | ./analyze.md > results.txt ``` ```markdown theme={null} #!/usr/bin/env ai Analyze the JSON data provided on stdin. Summarize key trends and outliers. ``` Read-only analysis of piped input doesn't need permission flags. ### Code Review with Provider Selection ```markdown theme={null} #!/usr/bin/env -S ai --aws --opus Review the code in this repository for security vulnerabilities. Focus on OWASP Top 10 issues. Be specific about file and line numbers. ``` ### Composable Script Chains Chain scripts together like Unix programs: ```bash theme={null} ./parse.md | ./generate.md | ./review.md > final.txt ``` **Important:** Child scripts in pipelines should be simple prompt mode (without `--cc`). Only the top-level dispatcher should have tool access. ## Security Warnings **`--skip`, `--bypass`, `--permission-mode bypassPermissions`, and `--dangerously-skip-permissions` all give the AI full access to your system.** Use them carefully: * Only run trusted scripts in trusted directories * Prefer `--allowedTools` for granular control when full access isn't needed * In CI/CD, run inside containers or sandboxed environments * Never pipe untrusted remote scripts with bypass permissions: ```bash theme={null} # DANGEROUS — don't do this curl https://untrusted-site.com/script.md | ai --skip ``` ## Quick Reference \| I want to... | Shebang | \|--------------|---------|| \| Analyze code (read-only) | `#!/usr/bin/env ai` | \| Use a specific provider | `#!/usr/bin/env -S ai --aws` | \| Run commands and write files | `#!/usr/bin/env -S ai --skip` | \| Restrict to specific tools | `#!/usr/bin/env -S ai --allowedTools 'Bash(npm test)' 'Read'` | \| Full automation with provider | `#!/usr/bin/env -S ai --aws --opus --skip` | ## Next Steps Use YAML front-matter to make scripts reusable with CLI overrides Stream progress in real-time for long-running scripts Deep dive into permission modes and security best practices Run scripts in CI/CD pipelines with proper error handling # Script Variables Source: https://docs.airun.me/guides/variables Make scripts reusable with YAML front-matter and CLI overrides ## Overview Script variables let you write reusable markdown scripts with customizable parameters. Users can override variables from the command line without editing the script itself. ## YAML Front-Matter Syntax Declare variables in a YAML front-matter block at the top of your script: ```markdown theme={null} #!/usr/bin/env -S ai --haiku --- vars: topic: "machine learning" style: casual audience: --- Write a summary of {{topic}} in {{style}} style. Target audience: {{audience}}. ``` ### Syntax Rules * **Opt-in:** Variables only activate when front-matter contains `vars:`. No `vars:` = no behavior change. * **Front-matter stripped:** The `---` block is removed from the prompt when `vars:` is present. * **Default values:** Variables can have default values (like `topic: "machine learning"`) * **No default:** Variables declared with just the key (like `audience:`) have no default value ## Placeholder Substitution Use `{{varname}}` syntax to insert variable values into your prompt: ```markdown theme={null} Write a {{length}} summary of {{topic}} in a {{style}} tone. ``` The `{{placeholder}}` syntax: * Doesn't collide with shell variables (`$VAR`) * Doesn't collide with markdown syntax * Doesn't collide with Claude syntax * Is visually distinct and easy to read ### Unset Variables A variable declared with no default (just `key:`) and no CLI override leaves `{{key}}` as-is in the prompt: ```markdown theme={null} --- vars: topic: --- Summarize {{topic}}. ``` Without `--topic` flag: "Summarize ." (literal text) With `--topic "AI"`: "Summarize AI." ## CLI Overrides Override variables from the command line using flag syntax: ```bash theme={null} ./script.md --varname value ./script.md --varname="value with spaces" ``` ### Examples Given this script: ```markdown summarize-topic.md theme={null} #!/usr/bin/env -S ai --haiku --- vars: topic: "machine learning" style: casual length: short --- Write a {{length}} summary of {{topic}} in a {{style}} tone. ``` Run with defaults: ```bash theme={null} ./summarize-topic.md # Uses: topic="machine learning", style=casual, length=short ``` Override one variable: ```bash theme={null} ./summarize-topic.md --topic "AI safety" # Uses: topic="AI safety", style=casual, length=short ``` Override multiple variables: ```bash theme={null} ./summarize-topic.md --topic "AI safety" --style formal # Uses: topic="AI safety", style=formal, length=short ``` Equals form works too: ```bash theme={null} ./summarize-topic.md --topic="robotics" --length="100 words" ``` ## Mixing with AI Runner Flags Variable overrides mix freely with AI Runner flags and provider overrides: ```bash theme={null} # --live is an AI Runner flag, --topic is a variable override ./summarize-topic.md --live --topic "quantum computing" # Override provider + model alongside variables ai --aws --opus summarize-topic.md --topic "the fall of rome" # All together ./summarize-topic.md --live --length "100 words" --topic "the fall of rome" --style "peter griffin" ``` ### How Flag Consumption Works Override flags matching declared var names are consumed by the variable system — they don't pass through to Claude Code: * `--topic`, `--style`, `--length` are consumed (match declared vars) * `--live`, `--aws`, `--opus` pass through to AI Runner * Unrecognized flags (like `--verbose`) pass through to Claude Code ## Complete Example Here's a real-world script with variables: ```markdown summarize-topic.md theme={null} #!/usr/bin/env -S ai --haiku --- vars: topic: "machine learning" style: casual length: short --- Write a {{length}} summary of {{topic}} in a {{style}} tone. ``` ### Usage Examples **Default behavior:** ```bash theme={null} ./summarize-topic.md ``` Output: Short, casual summary of machine learning **Override topic:** ```bash theme={null} ./summarize-topic.md --topic "quantum computing" ``` Output: Short, casual summary of quantum computing **Override all variables:** ```bash theme={null} ./summarize-topic.md \ --topic "the fall of rome" \ --style "peter griffin" \ --length "100 words" ``` Output: 100-word summary of the fall of Rome in Peter Griffin's style **With live streaming:** ```bash theme={null} ./summarize-topic.md --live --topic "AI safety" ``` Output: Streams the summary in real-time **With provider override:** ```bash theme={null} ai --aws --opus summarize-topic.md --topic "climate change" --style formal ``` Uses AWS Bedrock with Claude Opus, formal style summary of climate change ## Advanced Patterns ### Optional vs Required Variables **Optional (with default):** ```markdown theme={null} --- vars: format: markdown verbose: false --- Generate output in {{format}} format. Verbose mode: {{verbose}}. ``` **Required (no default):** ```markdown theme={null} --- vars: target_file: operation: --- Perform {{operation}} on {{target_file}}. ``` Users must provide `--target_file` and `--operation` or the placeholders remain literal. ### Multiple Scripts with Shared Variables Create a family of scripts that accept the same variables: ```markdown analyze.md theme={null} --- vars: language: python depth: basic --- Analyze {{language}} code with {{depth}} depth. ``` ```markdown review.md theme={null} --- vars: language: python depth: basic --- Review {{language}} code for {{depth}} issues. ``` Both scripts accept the same flags: ```bash theme={null} ./analyze.md --language go --depth thorough ./review.md --language go --depth thorough ``` ### Pipeline with Variables Pass variables through a pipeline: ```bash theme={null} ./extract.md --source data.json | \ ./transform.md --format csv | \ ./validate.md --schema schema.json > output.csv ``` Each script in the pipeline can have its own variables. ## Common Use Cases ### 1. Documentation Generator ```markdown generate-docs.md theme={null} #!/usr/bin/env -S ai --skip --- vars: source_dir: src output_file: ARCHITECTURE.md style: technical --- Read files in {{source_dir}}/ Generate {{output_file}} documenting the codebase. Use {{style}} writing style. ``` Usage: ```bash theme={null} ./generate-docs.md ./generate-docs.md --source_dir lib --output_file README.md --style casual ``` ### 2. Test Runner ```markdown run-tests.md theme={null} #!/usr/bin/env -S ai --skip --- vars: test_pattern: "*.test.js" framework: jest coverage: false --- Run tests matching {{test_pattern}} using {{framework}}. Generate coverage report: {{coverage}}. ``` Usage: ```bash theme={null} ./run-tests.md ./run-tests.md --test_pattern "integration/*.test.ts" --coverage true ``` ### 3. Code Reviewer ```markdown review.md theme={null} #!/usr/bin/env -S ai --opus --- vars: focus: security severity: high output_format: markdown --- Review code for {{focus}} issues. Only report {{severity}} severity and above. Output in {{output_format}} format. ``` Usage: ```bash theme={null} ./review.md ./review.md --focus performance --severity medium --output_format json ``` ### 4. Data Analyzer ```markdown analyze-data.md theme={null} #!/usr/bin/env ai --- vars: metric: revenue period: monthly visualization: false --- Analyze {{metric}} trends over {{period}} periods. Include visualization: {{visualization}}. ``` Usage: ```bash theme={null} cat data.csv | ./analyze-data.md --metric users --period weekly ``` ## Best Practices **Do:** * Provide sensible defaults for optional parameters * Use descriptive variable names (`source_dir` not `src`) * Document expected values in comments * Keep variable names lowercase with underscores * Use boolean variables for feature flags (`verbose: false`) **Don't:** * Use variable names that conflict with AI Runner flags (`--live`, `--aws`) * Put sensitive data in default values (use environment variables instead) * Create too many variables (makes scripts hard to use) * Use complex variable names (`target_file_for_processing` → `target_file`) ## Troubleshooting ### Variables Not Substituting **Problem:** `{{topic}}` appears literally in output **Solutions:** 1. Check YAML syntax (must have `vars:` key) 2. Ensure front-matter is at the top of the file 3. Verify closing `---` after front-matter 4. Check variable is declared in `vars:` block ### CLI Override Not Working **Problem:** `--topic "AI"` doesn't override the default **Solutions:** 1. Check variable is declared in front-matter 2. Verify flag syntax: `--topic value` or `--topic="value"` 3. Check for typos in variable name 4. Ensure flag comes after script name: `./script.md --topic "AI"` ### Conflicts with Claude Code Flags **Problem:** `--format json` is interpreted as a variable instead of a Claude Code flag **Solution:** Don't declare variables with names that match Claude Code flags. Common conflicts to avoid: * `--live` * `--quiet` * `--output-format` * `--max-turns` ## Next Steps Learn script basics and common patterns Stream progress in real-time Use variables in CI/CD pipelines Control what scripts can do # Installation Source: https://docs.airun.me/installation Complete installation guide for Andi AIRun with provider configuration and verification # Installation This guide covers installation, configuration, and verification of Andi AIRun on all supported platforms. ## Supported Platforms * **macOS** 13.0+ * **Linux** (Ubuntu 20.04+, Debian 10+) * **Windows** 10+ via WSL ## Prerequisites Before installing AIRun, you need [Claude Code](https://claude.ai/code) installed on your system. ```bash theme={null} claude --version ``` If this command works, you already have Claude Code installed and can skip to the next section. If Claude Code is not installed, run: ```bash theme={null} curl -fsSL https://claude.ai/install.sh | bash ``` You'll need an active Claude subscription (Pro or Max) or API credentials to use Claude Code. ## Install AIRun ```bash theme={null} git clone https://github.com/andisearch/airun.git cd airun ``` ```bash theme={null} ./setup.sh ``` The setup script will: * Install commands to `/usr/local/bin` (may require sudo) * Create `~/.ai-runner/` configuration directory * Copy `secrets.example.sh` to `~/.ai-runner/secrets.sh` * Install library scripts to `/usr/local/share/ai-runner` * Migrate existing `~/.claude-switcher/` configuration if present The setup is **non-destructive**. Your plain `claude` command always works untouched as before. All AIRun operations are session-scoped and automatically restore your original configuration on exit. ```bash theme={null} ai --version ``` You should see the AIRun version number (e.g., `ai-runner v1.2.0`). ## Configure Providers AIRun supports multiple AI providers. You only need to configure the providers you want to use. ```bash theme={null} nano ~/.ai-runner/secrets.sh ``` This file contains templates for all supported providers. Uncomment and fill in the credentials for the providers you want to use. Choose the providers you want to configure: **Ollama** - Runs models locally or on Ollama's cloud: ```bash theme={null} # Install Ollama brew install ollama # macOS curl -fsSL https://ollama.com/install.sh | sh # Linux / WSL # Quick setup (Ollama 0.15+) ollama launch claude # Auto-configure and launch Claude Code # Or manual setup ollama pull qwen3-coder # Pull a model (needs 24GB+ VRAM) ai --ollama # Run with Ollama # Cloud models — no GPU required, runs on Ollama's servers ollama pull minimax-m2.5:cloud # Best coding (80% SWE-bench, MIT) ollama pull glm-5:cloud # Best reasoning (78% SWE-bench, MIT) ai --ollama --model minimax-m2.5:cloud ``` **Hardware note**: Coding models need 24GB+ VRAM (or unified memory on Apple Silicon). Ollama's cloud models work on any hardware. **LM Studio** - Local models with MLX support (fast on Apple Silicon): ```bash theme={null} # 1. Download from lmstudio.ai and load a model # 2. Start the server: lms server start --port 1234 ai --lm # Run with LM Studio ``` Add to `~/.ai-runner/secrets.sh`: ```bash theme={null} # Option 1: AWS Bedrock API Key (recommended for simplicity) export AWS_BEARER_TOKEN_BEDROCK="your-bedrock-api-key" # Option 2: AWS Access Keys export AWS_ACCESS_KEY_ID="your_access_key" export AWS_SECRET_ACCESS_KEY="your_secret_key" export AWS_SESSION_TOKEN="your_session_token" # Optional, for temporary credentials # Option 3: AWS Profile export AWS_PROFILE="your-profile-name" # Required for all AWS auth methods: export AWS_REGION="us-west-2" ``` See [Claude Code AWS Bedrock docs](https://code.claude.com/docs/en/amazon-bedrock) for more details. Add to `~/.ai-runner/secrets.sh`: ```bash theme={null} # Required export ANTHROPIC_VERTEX_PROJECT_ID="your_gcp_project_id" export CLOUD_ML_REGION="global" # or "us-east5", "us-central1", etc. ``` Google Cloud Authentication (in precedence order): 1. **Service Account Key File** (highest precedence, recommended for production/CI): ```bash theme={null} export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account-key.json" ``` 2. **Application Default Credentials** (recommended for local development): ```bash theme={null} gcloud auth application-default login # No additional environment variable needed ``` 3. **gcloud User Credentials** (fallback): ```bash theme={null} gcloud auth login # No additional environment variable needed ``` AIRun automatically detects and uses the appropriate method. See [Claude Code Vertex AI docs](https://code.claude.com/docs/en/google-vertex-ai) for more details. Add to `~/.ai-runner/secrets.sh`: ```bash theme={null} export ANTHROPIC_API_KEY="sk-ant-..." ``` Get your API key from [console.anthropic.com](https://console.anthropic.com/). Add to `~/.ai-runner/secrets.sh`: ```bash theme={null} # Option 1: API Key authentication export ANTHROPIC_FOUNDRY_API_KEY="your-azure-api-key" # Option 2: Use Azure default credential chain (az login) # If ANTHROPIC_FOUNDRY_API_KEY is not set, Azure default credentials will be used # Required: Azure resource name or full base URL export ANTHROPIC_FOUNDRY_RESOURCE="your-resource-name" # Or provide the full URL: # export ANTHROPIC_FOUNDRY_BASE_URL="https://your-resource-name.services.ai.azure.com" ``` See [Claude Code Azure docs](https://code.claude.com/docs/en/microsoft-foundry) for more details. Add to `~/.ai-runner/secrets.sh`: ```bash theme={null} export VERCEL_AI_GATEWAY_TOKEN="vck_..." export VERCEL_AI_GATEWAY_URL="https://ai-gateway.vercel.sh" # Default, can be customized ``` Get your token from the [Vercel dashboard](https://vercel.com/dashboard/~/ai). Vercel AI Gateway supports 100+ models from OpenAI, xAI, Google, Meta, and more. See [vercel.com/ai-gateway](https://vercel.com/ai-gateway). After adding your credentials, save and close the file. The `secrets.sh` file contains sensitive credentials. Keep it secure and never commit it to version control. ## Verify Configuration ```bash theme={null} ai-status ``` This command shows: * Current tool and provider * Authentication method * Configured models * Available providers Look for green checkmarks next to providers you've configured. ```bash theme={null} ai ``` This launches an interactive Claude Code session. You should see a message indicating which provider and model are active. Type `/status` in Claude to verify the authentication method. Try switching to different providers: ```bash theme={null} # Test Ollama (if configured) ai --ollama # Test AWS Bedrock (if configured) ai --aws # Test with specific model tier ai --vertex --opus ``` Each command should launch Claude Code with the specified provider. ## Model Configuration (Optional) AIRun uses sensible default models for each provider, but you can override them. ### Default Model Tiers AIRun provides three model tiers: * `--opus` / `--high` - Highest-tier model (Opus 4.6) * `--sonnet` / `--mid` - Mid-tier model (Sonnet 4.6, default for cloud providers) * `--haiku` / `--low` - Lowest-tier model (Haiku 4.5, fastest) ### Override Default Models To use different model versions, add overrides to `~/.ai-runner/secrets.sh`: ```bash theme={null} # AWS Bedrock Models export CLAUDE_MODEL_SONNET_AWS="global.anthropic.claude-sonnet-4-6" export CLAUDE_MODEL_OPUS_AWS="global.anthropic.claude-opus-4-6-v1" export CLAUDE_MODEL_HAIKU_AWS="us.anthropic.claude-haiku-4-5-20251001-v1:0" # Google Vertex Models export CLAUDE_MODEL_SONNET_VERTEX="claude-sonnet-4-6" export CLAUDE_MODEL_OPUS_VERTEX="claude-opus-4-6" export CLAUDE_MODEL_HAIKU_VERTEX="claude-haiku-4-5@20251001" # Anthropic API Models export CLAUDE_MODEL_SONNET_ANTHROPIC="claude-sonnet-4-6" export CLAUDE_MODEL_OPUS_ANTHROPIC="claude-opus-4-6" export CLAUDE_MODEL_HAIKU_ANTHROPIC="claude-haiku-4-5" ``` ### Dual Model Configuration Claude Code uses two models: 1. **`ANTHROPIC_MODEL`** - Main model for interactive work 2. **`ANTHROPIC_SMALL_FAST_MODEL`** - Background operations (defaults to Haiku) You can override the small/fast model: ```bash theme={null} # AWS Bedrock Small/Fast Model export CLAUDE_SMALL_FAST_MODEL_AWS="us.anthropic.claude-haiku-4-5-20251001-v1:0" ``` ## Set Default Provider Save your preferred provider and model as the default: ```bash theme={null} # Set default ai --aws --opus --set-default # Now 'ai' uses AWS + Opus by default ai task.md # Clear default ai --clear-default ``` ## Updating ```bash theme={null} ai update ``` Or manually: ```bash theme={null} cd airun && git pull && ./setup.sh ``` AIRun checks for updates once every 24 hours (non-blocking) and shows a notice when a new version is available. Your API keys in `~/.ai-runner/secrets.sh` are preserved during updates. Disable update checks by setting: `export AI_NO_UPDATE_CHECK=1` in your `~/.ai-runner/secrets.sh` ## Troubleshooting ### Common Issues 1. Verify API key: `grep ANTHROPIC_API_KEY ~/.ai-runner/secrets.sh` 2. Confirm you're using `ai` (not plain `claude`) 3. Run `ai-status` during the session 4. In Claude, run `/status` to see authentication method 1. Use `ai --pro` or plain `claude` 2. Run `/status` in Claude to verify authentication 1. Verify the server is running: ```bash theme={null} # For Ollama ollama list # For LM Studio curl http://localhost:1234/v1/models ``` 2. Check the host configuration in `~/.ai-runner/secrets.sh` 3. Ensure you have a model loaded The setup script needs write access to `/usr/local/bin`. If you see permission errors: ```bash theme={null} sudo ./setup.sh ``` The script will automatically request sudo access only if needed. ### Session-Scoped Behavior `ai` with no flags uses your regular Claude subscription, identical to running `claude` directly. Provider flags (`--aws`, `--ollama`, etc.) only affect the current session: * On exit, your original Claude settings are automatically restored * Plain `claude` in another terminal is completely unaffected * No global configuration is changed ## Uninstallation To remove AIRun: ```bash theme={null} cd airun ./uninstall.sh ``` This removes all installed commands and optionally removes the configuration directory. ## Next Steps Create and run your first executable AI script Explore example scripts and use cases Learn advanced scripting patterns Detailed provider setup and model recommendations # Introduction Source: https://docs.airun.me/introduction Run AI prompts like programs with executable markdown, Unix pipes, and cross-cloud provider switching # Andi AIRun Run AI prompts like programs. Executable markdown with shebang, Unix pipes, and output redirection. Extends Claude Code with cross-cloud provider switching and any-model support - free local or 100+ cloud models. ```bash theme={null} # Run Claude Code interactively: any model or provider ai # Regular Claude subscription (Pro, Max) ai --aws --opus --team --resume # Resume chats on AWS w/ Opus 4.6 + Agent Teams ai --ollama --bypass --model qwen3-coder # Ollama local model with bypassPermissions set ai --vercel --model openai/gpt-5.2-codex # Vercel AI Gateway with 100+ models # Run prompts like programs ai --azure --haiku script.md # Script automation cat data.json | ./analyze.md > results.txt ``` Get started in 5 minutes with your first executable AI script Detailed installation guide for all platforms Create markdown files that run as AI programs Switch between AWS, Azure, Vertex, Ollama, and more ## Overview Switch between your [Claude Code](https://claude.ai/code) subscription and different clouds + models: AWS Bedrock, Google Vertex, Azure, Vercel + Anthropic API. Supports free local models ([Ollama](https://ollama.com/), [LM Studio](https://lmstudio.ai/)) and 100+ alternate cloud models via [Vercel AI Gateway](https://vercel.com/ai-gateway) or Ollama Cloud. Swap and resume conversations mid-task to avoid rate limits and keep working. ## Key Features Create markdown files with `#!/usr/bin/env ai` shebang for script automation. Run them directly like any executable program. ```markdown theme={null} #!/usr/bin/env ai Analyze my codebase and summarize the architecture. ``` Make it executable and run: ```bash theme={null} chmod +x task.md ./task.md ``` Pipe data into scripts, redirect output, chain in pipelines — standard Unix semantics for AI automation. ```bash theme={null} cat data.json | ./analyze.md > results.txt # Pipe in, redirect out git log -10 | ./summarize.md # Feed git history to AI ./generate.md | ./review.md > final.txt # Chain scripts together ``` Use Claude on AWS, Vertex, Azure, Anthropic API + switch mid-conversation to bypass rate limits. Also supports local models and Vercel AI Gateway. ```bash theme={null} ai --aws # AWS Bedrock ai --vertex # Google Vertex AI ai --ollama # Ollama (local, free) ai --vercel # Vercel AI Gateway ``` Simple tier selection across all providers: `--opus`/`--high`, `--sonnet`/`--mid`, `--haiku`/`--low` ```bash theme={null} ai --opus task.md # Opus 4.6 (most capable) ai --sonnet task.md # Sonnet 4.6 ai --haiku task.md # Haiku 4.5 (fastest) ``` `--resume` picks up your previous chats with any model/provider. Switch providers mid-conversation when you hit rate limits. ```bash theme={null} # Hit rate limit on Claude Pro claude # "Rate limit exceeded. Try again in 4 hours." # Continue immediately with AWS ai --aws --resume ``` Declare variables with defaults in YAML front-matter. Users override them from the CLI without editing the script. ```markdown theme={null} #!/usr/bin/env -S ai --haiku --- vars: topic: "machine learning" style: casual length: short --- Write a {{length}} summary of {{topic}} in a {{style}} tone. ``` ```bash theme={null} ./summarize.md # uses defaults ./summarize.md --topic "AI safety" # overrides one variable ``` ## What it Does * **Executable markdown** with `#!/usr/bin/env ai` shebang for script automation * **Unix pipe support**: pipe data into scripts, redirect output, chain in pipelines * **Cross-cloud provider switching**: use Claude on AWS, Vertex, Azure, Anthropic API + switch mid-conversation to bypass rate limits. Also supports local models and Vercel AI Gateway * **Model tiers**: `--opus`/`--high`, `--sonnet`/`--mid`, `--haiku`/`--low` * **Session continuity**: `--resume` picks up your previous chats with any model/provider * **Non-destructive**: plain `claude` always works untouched as before From [Andi AI Search](https://andisearch.com). Star the [GitHub repo](https://github.com/andisearch/airun) if it helps! ## Supported Platforms * macOS 13.0+ * Linux (Ubuntu 20.04+, Debian 10+) * Windows 10+ via WSL ## Providers | Provider | Flag | Type | Notes | | ----------------- | --------------------- | ------------ | ------------------------------------------ | | Ollama | `--ollama` / `--ol` | Local | Free, no API costs, cloud option | | LM Studio | `--lmstudio` / `--lm` | Local | MLX models (fast on Apple Silicon) | | AWS Bedrock | `--aws` | Cloud | Requires AWS credentials | | Google Vertex AI | `--vertex` | Cloud | Requires GCP project | | Anthropic API | `--apikey` | Cloud | Direct API access | | Microsoft Azure | `--azure` | Cloud | Azure Foundry | | Vercel AI Gateway | `--vercel` | Cloud | Any model: OpenAI, xAI, Google, Meta, more | | Claude Pro | `--pro` | Subscription | Default if logged in | ## Next Steps Follow the quickstart guide to run your first executable AI script Complete installation instructions and configuration # Cloud Providers Source: https://docs.airun.me/providers/cloud Configure AWS, Google, Anthropic, Azure, and Vercel AI providers Cloud providers offer powerful AI models through APIs, with pay-as-you-go pricing and no local hardware requirements. ## AWS Bedrock AWS Bedrock provides Claude models through Amazon's infrastructure. ### Configuration Add to `~/.ai-runner/secrets.sh`: ```bash theme={null} export AWS_PROFILE="your-profile-name" export AWS_REGION="us-west-2" ``` ### Authentication Methods AWS Bedrock supports three authentication methods: #### 1. AWS Bedrock API Key (Recommended) ```bash theme={null} export AWS_BEARER_TOKEN_BEDROCK="your-bedrock-api-key" export AWS_REGION="us-west-2" ``` #### 2. AWS Access Keys ```bash theme={null} export AWS_ACCESS_KEY_ID="your_access_key" export AWS_SECRET_ACCESS_KEY="your_secret_key" export AWS_SESSION_TOKEN="your_session_token" # Optional export AWS_REGION="us-west-2" ``` #### 3. AWS Profile ```bash theme={null} export AWS_PROFILE="your-profile-name" export AWS_REGION="us-west-2" ``` ### Usage ```bash theme={null} # Use default tier (Sonnet) ai --aws # Use specific tier ai --aws --opus task.md ai --aws --sonnet task.md ai --aws --haiku quick-fix.md ``` ### Custom Models Override default models in `secrets.sh`: ```bash theme={null} export CLAUDE_MODEL_OPUS_AWS="global.anthropic.claude-opus-4-6-v1" export CLAUDE_MODEL_SONNET_AWS="global.anthropic.claude-sonnet-4-6" export CLAUDE_MODEL_HAIKU_AWS="us.anthropic.claude-haiku-4-5-20251001-v1:0" export CLAUDE_SMALL_FAST_MODEL_AWS="us.anthropic.claude-haiku-4-5-20251001-v1:0" ``` Read the complete AWS Bedrock setup guide *** ## Google Vertex AI Google Vertex AI provides Claude models through Google Cloud Platform. ### Configuration Add to `~/.ai-runner/secrets.sh`: ```bash theme={null} export ANTHROPIC_VERTEX_PROJECT_ID="your-gcp-project-id" export CLOUD_ML_REGION="global" ``` ### Authentication Vertex AI supports three authentication methods (in precedence order): #### 1. Service Account Key File ```bash theme={null} export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account-key.json" ``` #### 2. Application Default Credentials ```bash theme={null} gcloud auth application-default login ``` #### 3. User Credentials ```bash theme={null} gcloud auth login ``` ### Prerequisites 1. Install Google Cloud SDK: [https://cloud.google.com/sdk/docs/install](https://cloud.google.com/sdk/docs/install) 2. Authenticate with one of the methods above 3. Enable Claude models in Vertex AI Model Garden ### Usage ```bash theme={null} # Use default tier (Sonnet) ai --vertex # Use specific tier ai --vertex --opus task.md ai --vertex --sonnet task.md ai --vertex --haiku quick-fix.md ``` ### Custom Models Override default models in `secrets.sh`: ```bash theme={null} export CLAUDE_MODEL_OPUS_VERTEX="claude-opus-4-6" export CLAUDE_MODEL_SONNET_VERTEX="claude-sonnet-4-6" export CLAUDE_MODEL_HAIKU_VERTEX="claude-haiku-4-5@20251001" export CLAUDE_SMALL_FAST_MODEL_VERTEX="claude-haiku-4-5@20251001" ``` ### Regional Overrides For specific model regional availability: ```bash theme={null} export VERTEX_REGION_CLAUDE_4_6_OPUS="us-east5" export VERTEX_REGION_CLAUDE_4_6_SONNET="us-east5" ``` Read the complete Vertex AI setup guide *** ## Anthropic API Direct API access to Anthropic's Claude models. ### Configuration Add to `~/.ai-runner/secrets.sh`: ```bash theme={null} export ANTHROPIC_API_KEY="sk-ant-..." ``` ### Getting an API Key 1. Sign up at [console.anthropic.com](https://console.anthropic.com/) 2. Navigate to API Keys 3. Create a new API key 4. Add it to your `secrets.sh` ### Usage ```bash theme={null} # Use default tier (Sonnet) ai --apikey # Use specific tier ai --apikey --opus task.md ai --apikey --sonnet task.md ai --apikey --haiku quick-fix.md ``` ### Custom Models Override default models in `secrets.sh`: ```bash theme={null} export CLAUDE_MODEL_OPUS_ANTHROPIC="claude-opus-4-6" export CLAUDE_MODEL_SONNET_ANTHROPIC="claude-sonnet-4-6" export CLAUDE_MODEL_HAIKU_ANTHROPIC="claude-haiku-4-5" export CLAUDE_SMALL_FAST_MODEL_ANTHROPIC="claude-haiku-4-5" ``` If you're also logged into Claude Pro, you'll see an "Auth conflict" warning from Claude Code. This is normal - Claude Code will use the API key for billing. The warning is just informational. Read the Anthropic API documentation *** ## Microsoft Azure Microsoft Foundry on Azure provides Claude models through Azure. ### Configuration Add to `~/.ai-runner/secrets.sh`: ```bash theme={null} export ANTHROPIC_FOUNDRY_API_KEY="your-azure-api-key" export ANTHROPIC_FOUNDRY_RESOURCE="your-resource-name" ``` Or provide the full URL: ```bash theme={null} export ANTHROPIC_FOUNDRY_BASE_URL="https://your-resource-name.services.ai.azure.com" ``` ### Authentication Methods #### 1. API Key (Recommended) ```bash theme={null} export ANTHROPIC_FOUNDRY_API_KEY="your-azure-api-key" export ANTHROPIC_FOUNDRY_RESOURCE="your-resource-name" ``` #### 2. Azure Default Credentials ```bash theme={null} az login export ANTHROPIC_FOUNDRY_RESOURCE="your-resource-name" ``` ### Usage ```bash theme={null} # Use default tier (Sonnet) ai --azure # Use specific tier ai --azure --opus task.md ai --azure --sonnet task.md ai --azure --haiku quick-fix.md ``` ### Custom Models Azure model names are deployment names (user-defined). Override in `secrets.sh`: ```bash theme={null} export CLAUDE_MODEL_OPUS_AZURE="claude-opus-4-6" export CLAUDE_MODEL_SONNET_AZURE="claude-sonnet-4-6" export CLAUDE_MODEL_HAIKU_AZURE="claude-haiku-4-5" export CLAUDE_SMALL_FAST_MODEL_AZURE="claude-haiku-4-5" ``` Read the complete Microsoft Foundry setup guide *** ## Vercel AI Gateway Vercel AI Gateway provides unified access to 100+ models from multiple providers. ### Configuration Add to `~/.ai-runner/secrets.sh`: ```bash theme={null} export VERCEL_AI_GATEWAY_TOKEN="vck_..." export VERCEL_AI_GATEWAY_URL="https://ai-gateway.vercel.sh" # Optional ``` ### Getting a Token 1. Visit [vercel.com/dashboard/\~/ai](https://vercel.com/dashboard/~/ai) 2. Create a new AI Gateway token 3. Add it to your `secrets.sh` ### Usage with Claude Models ```bash theme={null} # Use default tier (Sonnet) ai --vercel # Use specific tier ai --vercel --opus task.md ai --vercel --sonnet task.md ai --vercel --haiku quick-fix.md ``` ### Use Any Model Vercel AI Gateway supports 100+ models from OpenAI, xAI, Google, Meta, Anthropic, Mistral, DeepSeek, and more — all through one API. Use `--model provider/model` to run Claude Code with any supported model: ```bash theme={null} ai --vercel --model xai/grok-code-fast-1 # xAI coding model ai --vercel --model openai/gpt-5.2-codex # OpenAI coding model ai --vercel --model google/gemini-3-pro-preview # Google reasoning model ai --vercel --model alibaba/qwen3-coder # Alibaba coding model ai --vercel --model zai/glm-5 # Zhipu AI GLM-5 198K context ``` ### Example Coding Models | Model ID | Provider | Description | | ----------------------------- | -------- | -------------------------------------------------- | | `xai/grok-code-fast-1` | xAI | Fast coding model | | `openai/gpt-5.2-codex` | OpenAI | Coding-optimized GPT (also `openai/gpt-5.3-codex`) | | `google/gemini-3-pro-preview` | Google | Latest reasoning model | | `alibaba/qwen3-coder` | Alibaba | Open-source coding model | | `zai/glm-5` | Zhipu AI | GLM-5, 198K context, MIT license | View all available models on Vercel AI Gateway ### Configuration for Non-Anthropic Models When using non-Anthropic models, configure defaults in `secrets.sh`: ```bash theme={null} # Use a non-Anthropic model as default for Vercel export CLAUDE_MODEL_SONNET_VERCEL="xai/grok-code-fast-1" # Set a specific background/small-fast model export CLAUDE_SMALL_FAST_MODEL_VERCEL="xai/grok-code-fast-1" ``` **Automatic small/fast model:** When you use `--model` with a non-Anthropic model (e.g., `xai/grok-code-fast-1`), the background model is automatically set to the same model. This avoids mixing providers (e.g., xAI for main work + Anthropic for background). For Anthropic models on Vercel, the background model defaults to Haiku as usual. ### Set as Default Provider ```bash theme={null} ai --vercel --model xai/grok-code-fast-1 --set-default ai --clear-default ``` *** ## Claude Pro Uses your Claude Pro/Max subscription. No API keys needed. ### Prerequisites * Claude Code installed * Logged in with Claude subscription: ```bash theme={null} claude login ``` ### Usage ```bash theme={null} # Use default tier (Sonnet) ai --pro # Use specific tier ai --pro --opus task.md ai --pro --sonnet task.md ai --pro --haiku quick-fix.md ``` This is the default provider if you're logged into Claude Code with a subscription. Claude Pro has rate limits. When you hit a limit, switch to an API provider with `--resume` to continue your work. *** ## Provider Comparison | Provider | Setup Complexity | Cost Model | Model Selection | Best For | | ----------------- | ---------------- | ------------ | ------------------ | ------------------------------ | | **Ollama** | Easy | Free | Open-source models | Local, privacy, cloud fallback | | **LM Studio** | Easy | Free | Custom models | Apple Silicon, custom models | | **AWS Bedrock** | Medium | Pay-per-use | Claude models | AWS integration | | **Vertex AI** | Medium | Pay-per-use | Claude models | GCP integration | | **Anthropic API** | Easy | Pay-per-use | Claude models | Direct access | | **Azure** | Medium | Pay-per-use | Claude models | Azure integration | | **Vercel** | Easy | Pay-per-use | 100+ models | Multi-provider access | | **Claude Pro** | Easiest | Subscription | Claude models | Rate limits exist | ## Next Steps Learn about the provider system Switch providers to avoid rate limits # Local Providers Source: https://docs.airun.me/providers/local Run AI models locally with Ollama or LM Studio Local providers run AI models on your hardware, offering free, private AI with no API costs. ## Hardware Requirements Running local models requires significant RAM/VRAM: * **Capable coding models** (30B+ parameters) need **24GB+ VRAM** or unified memory (Apple Silicon M2 Pro/Max and above) * **Smaller models** run on less hardware but may struggle with complex coding tasks * **Systems with limited VRAM**: Ollama's cloud models are an excellent free alternative — they run on Ollama's servers with no local GPU needed ### Recommended Hardware | Hardware | Capability | Recommended Models | | ------------------------------------- | ---------- | ------------------------------- | | **Apple Silicon M2 Pro/Max+** (32GB+) | High | qwen3-coder (local), MLX models | | **NVIDIA 3090/4090** (24GB+) | High | qwen3-coder, gpt-oss:20b | | **Mid-range GPU** (12-24GB) | Mid | gpt-oss:20b, qwen2.5-coder:14b | | **Low-end GPU** (under 12GB) | Low | Use Ollama Cloud models | | **CPU only** | Minimal | Use Ollama Cloud (recommended) | ## Ollama Ollama runs models locally (free) or on Ollama's cloud (no GPU needed). ### Installation ```bash macOS theme={null} brew install ollama ``` ```bash Linux / Windows (WSL) theme={null} curl -fsSL https://ollama.com/install.sh | sh ``` ### Quick Setup (Recommended) Ollama 0.15+ can auto-configure Claude Code: ```bash theme={null} ollama launch claude # Interactive setup, picks model, launches Claude ollama launch claude --config # Configure only, don't launch ``` ### Cloud Models (No GPU Required) Cloud models run on Ollama's infrastructure — ideal if your system doesn't have enough VRAM for local models. Pull the manifest first (tiny download, the model runs remotely): ```bash theme={null} ollama pull minimax-m2.5:cloud # Tiny download, runs remotely ai --ollama --model minimax-m2.5:cloud ``` #### Available Cloud Models | Cloud Model | SWE-bench | Params (active) | Best For | License | | -------------------- | --------- | --------------- | -------------------------- | ------- | | `minimax-m2.5:cloud` | 80.2% | 230B MoE (10B) | Coding, agentic workflows | MIT | | `glm-5:cloud` | 77.8% | 744B MoE (40B) | Reasoning, math, knowledge | MIT | See [Ollama cloud models](https://ollama.com/search?c=cloud) for the full list. ### Local Models (Free, Private) Local models require sufficient VRAM — 24GB+ recommended for capable coding models. ```bash theme={null} ollama pull qwen3-coder # Coding optimized (needs 24GB+ VRAM) ai --ollama ``` #### Recommended Local Models | Model | Size | VRAM Needed | Best For | | ------------------- | ---- | ----------- | --------------------------- | | `qwen3-coder` | 30B | \~28GB | Coding tasks, large context | | `gpt-oss:20b` | 20B | \~16GB | Strong general-purpose | | `qwen2.5-coder:14b` | 14B | \~12GB | Mid-range GPUs | | `qwen2.5-coder:7b` | 7B | \~8GB | Limited VRAM | ### Model Aliases Create aliases for tools expecting Anthropic model names: ```bash theme={null} ollama cp qwen3-coder claude-sonnet-4-6 ai --ollama --model claude-sonnet-4-6 ``` ### Configuration Override defaults in `~/.ai-runner/secrets.sh`: ```bash theme={null} export OLLAMA_MODEL_MID="qwen3-coder" # Default model export OLLAMA_SMALL_FAST_MODEL="qwen3-coder" # Background model (or leave empty to use same) ``` By default, Ollama uses the same model for both main and background operations to avoid VRAM swapping. Only set `OLLAMA_SMALL_FAST_MODEL` if you have 24GB+ VRAM. ### Auto-Download Feature When you specify a model that isn't installed locally, Andi AIRun offers a choice between local and cloud: ```bash theme={null} ai --ollama --model qwen3-coder # Model 'qwen3-coder' not found locally. # # Your system has ~32GB usable VRAM. # # Options: # 1) Pull local version (recommended) - qwen3-coder # 2) Use cloud version - qwen3-coder:cloud # # Choice [1]: 1 # Pulling model: qwen3-coder # [##################################################] 100% # Model pulled successfully ``` For systems with limited VRAM (\< 20GB), cloud is recommended first. ### Usage Examples ```bash theme={null} # Use default model ai --ollama # Use cloud model ai --ollama --model glm-5:cloud # Use specific local model ai --ollama --model qwen3-coder # Use with tier flags ai --ollama --opus # Uses OLLAMA_MODEL_HIGH if set ``` Learn more about Ollama's Anthropic API compatibility *** ## LM Studio LM Studio runs local models with Anthropic API compatibility. Especially powerful on Apple Silicon with MLX models. Requires sufficient RAM/VRAM for the model you choose. ### Advantages Over Ollama * **MLX model support** (significantly faster on Apple Silicon) * **GGUF + MLX formats** supported * **Bring your own models** from HuggingFace ### Installation Download from [lmstudio.ai](https://lmstudio.ai) ### Setup 1. **Download a model** in LM Studio (e.g., from HuggingFace) 2. **Load the model** in LM Studio UI 3. **Start the server:** ```bash theme={null} lms server start --port 1234 ``` Or start from the LM Studio app's local server tab. 4. **Run Andi AIRun:** ```bash theme={null} ai --lmstudio # or ai --lm ``` ### Recommended Models For Claude Code, use models with: * **25K+ context window** (required for Claude Code's heavy context usage) * **Function calling / tool use support** Examples: * `openai/gpt-oss-20b` - Strong general-purpose * `ibm/granite-4-micro` - Fast, efficient ### Apple Silicon Optimization LM Studio supports **MLX models** which are significantly faster than GGUF on M1/M2/M3/M4 chips. When downloading models, look for MLX versions for best performance. MLX models can be **2-3x faster** than GGUF on Apple Silicon due to optimized metal acceleration. ### Configuration Override defaults in `~/.ai-runner/secrets.sh`: ```bash theme={null} export LMSTUDIO_HOST="http://localhost:1234" # Custom server URL export LMSTUDIO_MODEL_MID="openai/gpt-oss-20b" # Default model export LMSTUDIO_MODEL_HIGH="openai/gpt-oss-20b" # High tier model export LMSTUDIO_MODEL_LOW="ibm/granite-4-micro" # Low tier model ``` By default, LM Studio uses the same model for all tiers and background operations to avoid model swapping. ### Context Window Configure context size in LM Studio: * **UI**: Settings → Context Length * **Minimum recommended**: 25K tokens * **Higher is better** for complex coding tasks ### Auto-Download Feature When you specify a model that isn't available, Andi AIRun will offer to download it: ```bash theme={null} ai --lm --model lmstudio-community/qwen3-8b-gguf # Model 'lmstudio-community/qwen3-8b-gguf' not found in LM Studio. # Download it? [Y/n]: y # Downloading model: lmstudio-community/qwen3-8b-gguf # Progress: 100.0% # Model downloaded successfully # Load it now? [Y/n]: y # Model loaded ``` ### Usage Examples ```bash theme={null} # Use default model ai --lmstudio # Use short alias ai --lm # Use specific model ai --lm --model openai/gpt-oss-20b # Use with tier flags ai --lm --opus # Uses LMSTUDIO_MODEL_HIGH if set ``` Learn more about using LM Studio with Claude Code *** ## Comparison: Ollama vs LM Studio | Feature | Ollama | LM Studio | | ----------------- | --------------------------- | ------------------------------- | | **Cloud models** | ✅ Yes (free) | ❌ No | | **MLX support** | ❌ No | ✅ Yes (faster on Apple Silicon) | | **Model formats** | Ollama format | GGUF, MLX | | **Model library** | Curated | HuggingFace, custom | | **Setup** | Command-line focused | GUI-focused | | **Best for** | Quick start, cloud fallback | Apple Silicon, custom models | ## Next Steps Configure cloud providers for more powerful models Learn to switch between providers seamlessly # Provider Overview Source: https://docs.airun.me/providers/overview Understanding AI providers in Andi AIRun Andi AIRun supports multiple AI providers, allowing you to choose between local models (free, private) and cloud APIs (powerful, scalable). ## Quick Reference | Flag | Provider | Type | Notes | | --------------------- | ----------------- | ------------ | ----------------------------------------------------- | | `--ollama` / `--ol` | Ollama | Local | Free, no API costs, cloud option | | `--lmstudio` / `--lm` | LM Studio | Local | MLX models (fast on Apple Silicon) | | `--aws` | AWS Bedrock | Cloud | Requires AWS credentials | | `--vertex` | Google Vertex AI | Cloud | Requires GCP project | | `--apikey` | Anthropic API | Cloud | Direct API access | | `--azure` | Microsoft Azure | Cloud | Azure Foundry | | `--vercel` | Vercel AI Gateway | Cloud | Any model: Anthropic, OpenAI, xAI, Google, Meta, more | | `--pro` | Claude Pro | Subscription | Default if logged in | ## How Configuration Works All provider credentials are stored in **one file**: `~/.ai-runner/secrets.sh` ### Initial Setup This file is created automatically by `./setup.sh` from the `secrets.example.sh` template: ```bash theme={null} nano ~/.ai-runner/secrets.sh ``` Andi AIRun loads this file at startup. You don't need to set environment variables in your shell profile or `.bashrc` — just add them to `secrets.sh`, and then switch providers freely with `ai --aws`, `ai --vertex`, etc. You only need to configure the providers you want to use. Configure multiple providers to switch between them when you hit rate limits or want to use different models. ### Session-Scoped Behavior All provider configurations are session-scoped: * Changes only affect the active terminal session * On exit, original settings automatically restore * Plain `claude` always runs in native state * Running `claude` in another terminal is unaffected This means you can safely run `ai --lmstudio` in one terminal while using `claude` normally in another. ## Provider Detection and Defaults ### Automatic Provider Selection If you don't specify a provider flag, Andi AIRun automatically detects and uses: 1. **Claude Pro** (if logged in with `claude login`) 2. **First configured provider** in secrets.sh ### Setting a Default Provider You can set a default provider to avoid typing the flag every time: ```bash theme={null} ai --vercel --model xai/grok-code-fast-1 --set-default ``` Clear the default: ```bash theme={null} ai --clear-default ``` ## Model Tier System Andi AIRun uses a three-tier model system to balance performance and cost: ### Tier Levels | Tier | Aliases | Use Case | Claude Models | | -------- | ------------------- | ---------------------------------- | ----------------- | | **High** | `--opus`, `--high` | Complex reasoning, large refactors | Claude Opus 4.6 | | **Mid** | `--sonnet`, `--mid` | General coding tasks (default) | Claude Sonnet 4.6 | | **Low** | `--haiku`, `--low` | Fast operations, small edits | Claude Haiku 4.5 | ### Usage Examples ```bash theme={null} # Use high tier for complex reasoning ai --aws --opus task.md # Use mid tier (default) ai --aws task.md # Use low tier for speed and cost savings ai --vertex --haiku simple-fix.md ``` ### Background Model Andi AIRun uses a "small/fast" model for background operations (like file searches, quick checks). By default, this is set to the **Low** tier model (Haiku). For local providers (Ollama, LM Studio), the background model defaults to the **same model** as the main tier to avoid costly model swapping. ## Configuring Model Tiers You can customize model tiers per provider in `secrets.sh`: ### Cloud Providers ```bash theme={null} # AWS Bedrock export CLAUDE_MODEL_OPUS_AWS="global.anthropic.claude-opus-4-6-v1" export CLAUDE_MODEL_SONNET_AWS="global.anthropic.claude-sonnet-4-6" export CLAUDE_MODEL_HAIKU_AWS="us.anthropic.claude-haiku-4-5-20251001-v1:0" # Google Vertex AI export CLAUDE_MODEL_OPUS_VERTEX="claude-opus-4-6" export CLAUDE_MODEL_SONNET_VERTEX="claude-sonnet-4-6" export CLAUDE_MODEL_HAIKU_VERTEX="claude-haiku-4-5@20251001" # Anthropic API export CLAUDE_MODEL_OPUS_ANTHROPIC="claude-opus-4-6" export CLAUDE_MODEL_SONNET_ANTHROPIC="claude-sonnet-4-6" export CLAUDE_MODEL_HAIKU_ANTHROPIC="claude-haiku-4-5" # Vercel AI Gateway export CLAUDE_MODEL_SONNET_VERCEL="xai/grok-code-fast-1" export CLAUDE_SMALL_FAST_MODEL_VERCEL="xai/grok-code-fast-1" ``` ### Local Providers ```bash theme={null} # Ollama export OLLAMA_MODEL_HIGH="qwen3-coder" export OLLAMA_MODEL_MID="qwen3-coder" export OLLAMA_MODEL_LOW="qwen2.5-coder:7b" export OLLAMA_SMALL_FAST_MODEL="qwen3-coder" # Same model to avoid swapping # LM Studio export LMSTUDIO_MODEL_HIGH="openai/gpt-oss-20b" export LMSTUDIO_MODEL_MID="openai/gpt-oss-20b" export LMSTUDIO_MODEL_LOW="ibm/granite-4-micro" export LMSTUDIO_SMALL_FAST_MODEL="openai/gpt-oss-20b" # Same model ``` ## Custom Models Override the tier system with a specific model: ```bash theme={null} # Use a specific model ai --vercel --model xai/grok-code-fast-1 # Use a specific Ollama model ai --ollama --model glm-5:cloud # Use a specific AWS model ai --aws --model global.anthropic.claude-opus-4-6-v1 ``` ## Agent Teams All providers support agent teams (`ai --team`). Coordination uses Claude Code's internal task list and mailbox, not provider-specific features. Read the Claude Code Agent Teams documentation ## Next Steps Set up Ollama or LM Studio for free, private AI Configure AWS, Google, Anthropic, Azure, or Vercel Learn to switch providers to avoid rate limits # Switching Between Providers Source: https://docs.airun.me/providers/switching Seamlessly switch providers to avoid rate limits and optimize costs Andi AIRun makes it easy to switch between providers mid-task, allowing you to work around rate limits, optimize costs, and leverage different models. ## Why Switch Providers? ### Avoid Rate Limits Claude Pro has usage limits. When you hit a rate limit, switch to an API provider and continue immediately: ```bash theme={null} # Working with Claude Pro, hit rate limit ai # "Rate limit exceeded. Try again in 4 hours 23 minutes." # Immediately continue with AWS ai --aws --resume ``` ### Optimize Costs Switch to cheaper models for simple tasks: ```bash theme={null} # Use Haiku for quick edits (faster, cheaper) ai --aws --haiku --resume # Use Ollama for free local inference ai --ollama --resume ``` ### Leverage Different Models Switch to more powerful models for complex reasoning: ```bash theme={null} # Switch to Opus for complex refactoring ai --aws --opus --resume # Try a different model entirely ai --vercel --model xai/grok-code-fast-1 --resume ``` ## Using --resume The `--resume` flag lets you pick up a previous conversation exactly where you left off. ### Basic Resume ```bash theme={null} # Start with Claude Pro ai # Hit rate limit, switch to AWS ai --aws --resume ``` ### Resume with Different Tier ```bash theme={null} # Working with Sonnet (default) ai --vertex # Switch to Haiku for speed ai --vertex --haiku --resume # Switch to Opus for complex reasoning ai --vertex --opus --resume ``` ### Resume with Different Provider ```bash theme={null} # Start with AWS ai --aws # Switch to Vertex AI ai --vertex --resume # Switch to local Ollama (free!) ai --ollama --resume ``` ### Resume with Custom Model ```bash theme={null} # Start with Claude Sonnet ai --vercel # Switch to xAI Grok ai --vercel --model xai/grok-code-fast-1 --resume ``` ## Session Continuity When you use `--resume`, Andi AIRun: 1. **Loads the previous conversation** from your most recent session 2. **Preserves all context** (files, code, decisions) 3. **Switches the provider** seamlessly 4. **Continues the task** without interruption The conversation history is stored locally in `~/.ai-runner/sessions/`, so resume works even after closing your terminal. ## Setting a Default Provider Avoid typing the provider flag every time by setting a default: ```bash theme={null} # Set AWS Bedrock as default ai --aws --set-default # Now 'ai' uses AWS automatically ai ai --opus ai --haiku ``` ### Setting Default with Custom Model ```bash theme={null} # Set Vercel with xAI Grok as default ai --vercel --model xai/grok-code-fast-1 --set-default # Now 'ai' uses xAI Grok automatically ai ``` ### Clearing the Default ```bash theme={null} ai --clear-default # Now 'ai' uses Claude Pro (if logged in) or first configured provider ai ``` ### Overriding the Default ```bash theme={null} # Set AWS as default ai --aws --set-default # Override for one session ai --vertex # Next session uses AWS again ai ``` ## Session Isolation All provider changes are **session-scoped** and **automatically isolated**: ### Terminal Isolation ```bash theme={null} # Terminal 1: Using LM Studio ai --lmstudio # Terminal 2: Using native Claude Pro (unaffected) claude # Terminal 3: Using AWS Bedrock ai --aws ``` Each terminal session is completely independent. ### Auto-Cleanup on Exit ```bash theme={null} ai --lmstudio # Session ends (Ctrl+C or naturally) # Original environment automatically restored # No stale state, no files modified ``` ### Process Safety * **No global state** - changes only affect the current terminal session * **No config files modified** - all changes via environment variables * **Crash-safe** - no cleanup needed if the session crashes * **Multiple sessions** - run different providers simultaneously ## Common Switching Patterns ### Pattern 1: Rate Limit Recovery ```bash theme={null} # Hit rate limit ai # "Rate limit exceeded. Try again in 4 hours 23 minutes." # Option 1: Switch to API provider ai --aws --resume # Option 2: Switch to free local ai --ollama --resume # Option 3: Switch to different cloud ai --vertex --resume ``` ### Pattern 2: Cost Optimization ```bash theme={null} # Start with powerful model for initial work ai --aws --opus # Switch to cheaper model for refinements ai --aws --haiku --resume # Switch to free local for final tweaks ai --ollama --resume ``` ### Pattern 3: Model Experimentation ```bash theme={null} # Try Claude Sonnet first ai --apikey # Not satisfied? Try xAI Grok ai --vercel --model xai/grok-code-fast-1 --resume # Try OpenAI's coding model ai --vercel --model openai/gpt-5.2-codex --resume # Try local model ai --ollama --model qwen3-coder --resume ``` ### Pattern 4: Development Workflow ```bash theme={null} # Planning phase: Use powerful model ai --aws --opus # Implementation: Use balanced model ai --aws --sonnet --resume # Testing/debugging: Use fast, cheap model ai --aws --haiku --resume # Refinement: Use free local ai --ollama --resume ``` ## Provider-Specific Considerations ### Local Providers (Ollama, LM Studio) **Pros:** * Free (no API costs) * No rate limits * Private (data stays local) * Fast (no network latency) **Cons:** * Requires hardware (VRAM/RAM) * Model quality varies * Setup required **Best used for:** * Cost-conscious development * Private/sensitive code * Frequent iterations * Learning and experimentation ### Cloud Providers (AWS, Vertex, Anthropic) **Pros:** * Most powerful models * No hardware requirements * Always available * Latest model versions **Cons:** * Pay per use * Rate limits (especially Claude Pro) * Network dependency * Data sent to provider **Best used for:** * Complex reasoning * Large refactors * Production work * Critical tasks ### Vercel AI Gateway **Pros:** * Access to 100+ models * Single API for all providers * Unified billing * Easy switching **Cons:** * Pay per use * Network dependency * Rate limits vary by model **Best used for:** * Multi-model workflows * Experimentation * Provider flexibility ## Tips for Effective Switching ### 1. Configure Multiple Providers Set up 2-3 providers in `secrets.sh` for maximum flexibility: ```bash theme={null} # Primary: Claude Pro (free tier) # Logged in with: claude login # Fallback 1: AWS Bedrock (pay-as-you-go) export AWS_PROFILE="my-profile" export AWS_REGION="us-west-2" # Fallback 2: Ollama (free local) # Just install and run: ollama serve ``` ### 2. Use Tier Flags for Cost Control ```bash theme={null} # Expensive: Opus for complex tasks ai --aws --opus complex-refactor.md # Balanced: Sonnet (default) for most work ai --aws task.md # Cheap: Haiku for simple edits ai --aws --haiku simple-fix.md ``` ### 3. Set Defaults for Common Workflows ```bash theme={null} # Set your most-used provider as default ai --aws --set-default # Clear when switching projects ai --clear-default ``` ### 4. Monitor Usage and Costs Keep an eye on your API usage: * AWS: CloudWatch metrics * Google: Cloud Console * Anthropic: Console dashboard * Vercel: AI Gateway dashboard ### 5. Use Local for Development ```bash theme={null} # Development: Use free local models ai --ollama # Production: Switch to cloud for reliability ai --aws --resume ``` ## Troubleshooting ### Resume Not Working ```bash theme={null} # Check session history ls ~/.ai-runner/sessions/ # Resume last session explicitly ai --resume # Resume specific session ai --resume --session 2024-03-03-15-30-00 ``` ### Provider Not Responding ```bash theme={null} # Test provider configuration ai --aws --test # Switch to known-good provider ai --apikey --resume ``` ### Model Not Available ```bash theme={null} # For local providers, pull/download first ollama pull qwen3-coder lms load openai/gpt-oss-20b # Then retry ai --ollama --model qwen3-coder --resume ``` ## Next Steps Learn about the provider system Set up free local models Configure cloud APIs # Quickstart Source: https://docs.airun.me/quickstart Get started with AIRun in 5 minutes - install, create your first executable AI script, and run it # Quickstart Get AIRun running in 5 minutes. This guide will help you install AIRun, create your first executable AI script, and run it. ## Prerequisites Before you begin, make sure you have [Claude Code](https://claude.ai/code) installed. AIRun extends Claude Code with executable markdown and provider switching. ```bash theme={null} # Install Claude Code (if not already installed) curl -fsSL https://claude.ai/install.sh | bash ``` Claude Code is Anthropic's AI coding CLI. You'll need an active Claude subscription (Pro or Max) or API credentials to use it. ## Installation ```bash theme={null} git clone https://github.com/andisearch/airun.git cd airun ``` ```bash theme={null} ./setup.sh ``` The setup script will: * Install commands to `/usr/local/bin` * Create `~/.ai-runner/` for configuration * Copy a secrets template for API keys The setup is non-destructive. Your plain `claude` command always works unchanged. ```bash theme={null} ai --version ``` You should see the AIRun version number. ## Your First Executable AI Script Let's create a simple executable markdown file that runs as an AI program. Create a file called `hello.md` with the following content: ```markdown hello.md theme={null} #!/usr/bin/env -S ai --haiku Say hello and briefly explain what you can do. ``` The first line is a shebang that tells the system to run this file with AIRun using the Haiku model (fastest and most cost-effective). ```bash theme={null} chmod +x hello.md ``` ```bash theme={null} ./hello.md ``` The AI will execute your prompt and respond. This uses your Claude subscription by default. You can also run any markdown file without making it executable: ```bash theme={null} ai hello.md ``` ## Example: Piping Data One of AIRun's most powerful features is Unix-style piping. Let's create a script that analyzes data: ```markdown analyze-code.md theme={null} #!/usr/bin/env -S ai --sonnet --skip Summarize the architecture of this codebase. List the main entry points, key modules, and how data flows through the system. ``` The `--skip` flag is shorthand for `--dangerously-skip-permissions`, which gives the AI full system access. Only use it in trusted directories with trusted scripts. Make it executable and run it: ```bash theme={null} chmod +x analyze-code.md ./analyze-code.md ``` ## Example: Script Variables Create reusable scripts with customizable variables: ```markdown summarize-topic.md theme={null} #!/usr/bin/env -S ai --haiku --- vars: topic: "machine learning" style: casual length: short --- Write a {{length}} summary of {{topic}} in a {{style}} tone. ``` Run with defaults or override variables: ```bash theme={null} # Use defaults ./summarize-topic.md # Override variables ./summarize-topic.md --topic "AI safety" --style formal --length detailed ``` ## Example: Unix Pipes Pipe data into your AI scripts: ```bash theme={null} # Analyze JSON data cat data.json | ./analyze.md > results.txt # Summarize git history git log --oneline -20 | ./summarize-changes.md # Chain scripts together ./generate-report.md | ./format-output.md > final.txt ``` ## Switch Providers Use different AI providers by adding flags: ```bash theme={null} # Use local Ollama (free!) ai --ollama hello.md # Use AWS Bedrock with Opus ai --aws --opus hello.md # Use Google Vertex AI ai --vertex hello.md # Use Vercel AI Gateway with a specific model ai --vercel --model openai/gpt-5.2-codex hello.md ``` You'll need to configure your API credentials for cloud providers. See the [Installation Guide](/installation) for details. ## Available Commands AIRun installs these commands: | Command | Description | | -------------- | ----------------------------------------------------- | | `ai` / `airun` | Universal entry point - run scripts, switch providers | | `ai update` | Update AI Runner to the latest version | | `ai-sessions` | View active AI coding sessions | | `ai-status` | Show current configuration and provider status | ## Next Steps Detailed installation and configuration instructions Configure AWS, Azure, Vertex, and other providers More example scripts and use cases Learn advanced scripting patterns and automation ## Tips **Use `#!/usr/bin/env -S` for shebangs with flags** Standard `env` only accepts one argument, so you need `-S` to pass multiple flags: ```markdown theme={null} #!/usr/bin/env -S ai --aws --opus ``` **Flag precedence**: CLI flags > shebang flags > saved defaults Running `ai --vercel task.md` overrides the script's shebang provider. **Set a default provider** ```bash theme={null} ai --ollama --set-default ai task.md # uses Ollama by default ai --clear-default # remove saved default ```