diff --git a/README.md b/README.md index 8e9b96335..788356821 100644 --- a/README.md +++ b/README.md @@ -21,72 +21,51 @@ Fork of badlogic/pi-mono by @mariozechner

---- +## Table of Contents -## Installation - -### Via Bun (recommended) - -Requires [Bun](https://bun.sh) runtime: - -```bash -bun install -g @oh-my-pi/pi-coding-agent -``` - -### Via installer script - -**Linux / macOS:** - -```bash -curl -fsSL https://raw.githubusercontent.com/can1357/oh-my-pi/main/scripts/install.sh | sh -``` - -**Windows (PowerShell):** - -```powershell -irm https://raw.githubusercontent.com/can1357/oh-my-pi/main/scripts/install.ps1 | iex -``` - -By default, the installer uses bun if available, otherwise downloads the prebuilt binary. - -Options: - -- `--source` / `-Source`: Install via bun (installs bun first if needed) -- `--binary` / `-Binary`: Always use prebuilt binary -- `--ref ` / `-Ref `: Install a tag/commit/branch (defaults to source install) - -```bash -# Force bun installation -curl -fsSL .../install.sh | sh -s -- --source - -# Install a tag via binary -curl -fsSL .../install.sh | sh -s -- --binary --ref v3.20.1 - -# Install a branch or commit via source -curl -fsSL .../install.sh | sh -s -- --source --ref main -``` - -```powershell -# Install a tag via binary -& ([scriptblock]::Create((irm https://raw.githubusercontent.com/can1357/oh-my-pi/main/scripts/install.ps1))) -Binary -Ref v3.20.1 - -# Install a branch or commit via source -& ([scriptblock]::Create((irm https://raw.githubusercontent.com/can1357/oh-my-pi/main/scripts/install.ps1))) -Source -Ref main -``` - -### Via [mise](https://mise.jdx.dev) - -```bash -mise use -g github:can1357/oh-my-pi -``` - -### Manual download - -Download binaries directly from [GitHub Releases](https://github.com/can1357/oh-my-pi/releases/latest). +- [Highlights](#highlights) +- [Installation](#installation) +- [Getting Started](#getting-started) + - [Terminal Setup](#terminal-setup) + - [API Keys & OAuth](#api-keys--oauth) + - [First 15 Minutes (Recommended)](#first-15-minutes-recommended) +- [Usage](#usage) + - [Slash Commands](#slash-commands) + - [Editor Features](#editor-features) + - [Keyboard Shortcuts](#keyboard-shortcuts) + - [Bash Mode](#bash-mode) + - [Image Support](#image-support) +- [Sessions](#sessions) + - [Session Management](#session-management) + - [Context Compaction](#context-compaction) + - [Branching](#branching) +- [Configuration](#configuration) + - [Project Context Files](#project-context-files) + - [Custom System Prompt](#custom-system-prompt) + - [Custom Models and Providers](#custom-models-and-providers) + - [Settings File](#settings-file) +- [Extensions](#extensions) + - [Themes](#themes) + - [Custom Slash Commands](#custom-slash-commands) + - [Skills](#skills) + - [Hooks](#hooks) + - [Custom Tools](#custom-tools) +- [CLI Reference](#cli-reference) +- [Tools](#tools) +- [Programmatic Usage](#programmatic-usage) + - [SDK](#sdk) + - [RPC Mode](#rpc-mode) + - [HTML Export](#html-export) +- [Philosophy](#philosophy) +- [Development](#development) +- [Monorepo Packages](#monorepo-packages) +- [License](#license) --- -## + Commit Tool (AI-Powered Git Commits) +## Highlights + +### + Commit Tool (AI-Powered Git Commits) AI-powered conventional commit generation with intelligent change analysis: @@ -98,25 +77,24 @@ AI-powered conventional commit generation with intelligent change analysis: - **Legacy mode**: `--legacy` flag for deterministic pipeline when preferred - Run via `omp commit` with options: `--push`, `--dry-run`, `--no-changelog`, `--context` -## + Python Tool (IPython Kernel) +### + Python Tool (IPython Kernel)

python

-Execute Python code with a persistent IPython kernel and 30+ shell-like helpers: +Execute Python code with a persistent IPython kernel and rich helper prelude: - **Streaming output**: Real-time stdout/stderr with image and JSON rendering -- **Prelude helpers**: `cat()`, `sed()`, `rsed()`, `find()`, `grep()`, `batch()`, `sh()`, `run()` and more -- **Git utilities**: `git_status()`, `git_diff()`, `git_log()`, `git_show()` for repository operations -- **Line operations**: `extract_lines()`, `delete_lines()`, `insert_lines()`, `lines_matching()` for text manipulation +- **Prelude helpers**: File I/O, search, find/replace, line operations, shell, and text utilities built into the kernel +- **Line operations**: `lines()`, `insert_at()`, `delete_lines()`, `delete_matching()` and related helpers for precise edits - **Shared gateway**: Resource-efficient kernel reuse across sessions (`python.sharedGateway` setting) -- **Custom modules**: Load extensions from `.omp/modules/` and `.pi/modules/` directories +- **Custom modules**: Load extensions from `.omp/modules/` and `~/.omp/agent/modules/` - **Rich output**: Supports `display()` for HTML, Markdown, images, and interactive JSON trees - **Mermaid diagrams**: Renders mermaid code blocks as inline graphics in iTerm2/Kitty terminals - Install dependencies via `omp setup python` -## + LSP Integration (Language Server Protocol) +### + LSP Integration (Language Server Protocol)

lsp @@ -126,12 +104,12 @@ Full IDE-like code intelligence with automatic formatting and diagnostics: - **Format-on-write**: Auto-format code using the language server's formatter (rustfmt, gofmt, prettier, etc.) - **Diagnostics on write/edit**: Immediate feedback on syntax errors and type issues after every file change -- **Workspace diagnostics**: Check entire project for errors (`lsp action=workspace_diagnostics`) +- **Workspace diagnostics**: Check entire project for errors with `lsp` action `diagnostics` (without a file) - **40+ language configs**: Out-of-the-box support for Rust, Go, Python, TypeScript, Java, Kotlin, Scala, Haskell, OCaml, Elixir, Ruby, PHP, C#, Lua, Nix, and many more - **Local binary resolution**: Auto-discovers project-local LSP servers in `node_modules/.bin/`, `.venv/bin/`, etc. - Hover docs, symbol references, code actions, workspace-wide symbol search -## + Time Traveling Streamed Rules (TTSR) +### + Time Traveling Streamed Rules (TTSR)

ttsr @@ -147,7 +125,7 @@ Zero context-use rules that inject themselves only when needed: Example: A "don't use deprecated API" rule only activates when the model starts writing deprecated code, saving context for sessions that never touch that API. -## + Interactive Code Review +### + Interactive Code Review

review @@ -160,7 +138,7 @@ Structured code review with priority-based findings: - **Verdict rendering**: aggregates findings into approve/request-changes/comment - Combined result tree showing verdict and all findings -## + Task Tool (Subagent System) +### + Task Tool (Subagent System)

task @@ -168,15 +146,15 @@ Structured code review with priority-based findings: Parallel execution framework with specialized agents and real-time streaming: -- **5 bundled agents**: explore, plan, browser, task, reviewer +- **6 bundled agents**: explore, plan, designer, reviewer, task, quick_task - **Parallel exploration**: Reviewer agent can spawn explore agents for large codebase analysis - **Real-time artifact streaming**: Task outputs stream as they're created, not just at completion -- **Output tool**: Read full agent outputs by ID when truncated previews aren't sufficient +- **Full output access**: Read complete subagent output via `agent://` resources when previews truncate - **Isolated execution**: `isolated: true` runs tasks in git worktrees, generates patches, and applies cleanly - User-level (`~/.omp/agent/agents/`) and project-level (`.omp/agents/`) custom agents - Concurrency-limited batch execution with progress tracking -## + Model Roles +### + Model Roles

models @@ -184,23 +162,23 @@ Parallel execution framework with specialized agents and real-time streaming: Configure different models for different purposes with automatic discovery: -- **Three roles**: `default` (main model), `smol` (fast/cheap), `slow` (comprehensive reasoning) -- **Auto-discovery**: Smol finds haiku → flash → mini; Slow finds codex → gpt → opus → pro +- **Role-based routing**: `default`, `smol`, `slow`, `plan`, and `commit` roles +- **Configurable discovery**: Role defaults are auto-resolved and can be overridden per role - **Role-based selection**: Task tool agents can use `model: pi/smol` for cost-effective exploration -- CLI args (`--smol`, `--slow`) and env vars (`PI_SMOL_MODEL`, `PI_SLOW_MODEL`) -- Configure via `/model` selector with keybindings (Enter=default, S=smol, L=slow) +- CLI args (`--smol`, `--slow`, `--plan`) and env vars (`PI_SMOL_MODEL`, `PI_SLOW_MODEL`, `PI_PLAN_MODEL`) +- Configure roles interactively via `/model` selector and persist assignments to settings -## + Todo Tool (Task Tracking) +### + Todo Tool (Task Tracking) Structured task management with persistent visual tracking: - **`todo_write` tool**: Create and manage task lists during coding sessions - **Persistent panel**: Todo list displays above the editor with real-time progress - **Task states**: `pending`, `in_progress`, `completed` with automatic status updates -- **Completion reminders**: Agent warned when stopping with incomplete todos (`todoCompletion` setting) +- **Completion reminders**: Agent warned when stopping with incomplete todos (`todo.reminders` setting) - **Toggle visibility**: `Ctrl+T` expands/collapses the todo panel -## + Ask Tool (Interactive Questioning) +### + Ask Tool (Interactive Questioning)

ask @@ -212,7 +190,7 @@ Structured user interaction with typed options: - **Multi-select support**: Allow multiple answers when choices aren't mutually exclusive - **Multi-part questions**: Ask multiple related questions in sequence via `questions` array parameter -## + Custom TypeScript Slash Commands +### + Custom TypeScript Slash Commands

slash @@ -226,7 +204,7 @@ Programmable commands with full API access: - Return string to send as LLM prompt, or void for fire-and-forget actions - Also loads from Claude Code directories (`~/.claude/commands/`, `.claude/commands/`) -## + Universal Config Discovery +### + Universal Config Discovery

discovery @@ -238,10 +216,10 @@ Unified capability-based discovery that loads configuration from 8 AI coding too - **Discovers everything**: MCP servers, rules, skills, hooks, tools, slash commands, prompts, context files - **Native format support**: Cursor MDC frontmatter, Windsurf rules, Cline `.clinerules`, Copilot `applyTo` globs, Gemini `system.md`, Codex `AGENTS.md` - **Provider attribution**: See which tool contributed each configuration item -- **Discovery settings**: Enable/disable individual providers via `/config` interactive tab -- **Priority ordering**: Multi-path resolution across `.omp`, `.pi`, and `.claude` directories +- **Discovery settings**: Enable/disable individual providers via `/extensions` interactive dashboard +- **Priority ordering**: Multi-path resolution across `.omp`, `.claude`, `.codex`, and `.gemini` directories -## + MCP & Plugin System +### + MCP & Plugin System

perplexity @@ -254,21 +232,21 @@ Full Model Context Protocol support with external tool integration: - Hot-loadable plugins from `~/.omp/plugins/` with npm/bun integration - Automatic Exa MCP server filtering with API key extraction -## + Web Search & Fetch +### + Web Search & Fetch

arxiv

-Multi-provider search and full-page scraping with 80+ specialized scrapers: +Multi-provider search and full-page scraping with specialized handlers: -- **Multi-provider search**: Anthropic, Perplexity, and Exa with automatic fallback chain -- **80+ site-specific scrapers**: GitHub, GitLab, npm, PyPI, crates.io, arXiv, PubMed, Stack Overflow, Hacker News, Reddit, Wikipedia, YouTube transcripts, and many more +- **Multi-provider search**: `auto`, `exa`, `jina`, `zai`, `anthropic`, `perplexity`, `gemini`, `codex` +- **Specialized handlers**: Site-specific extraction for code hosts, registries, research sources, forums, and docs - **Package registries**: npm, PyPI, crates.io, Hex, Hackage, NuGet, Maven, RubyGems, Packagist, pub.dev, Go packages - **Security databases**: NVD, OSV, CISA KEV vulnerability data - HTML-to-markdown conversion with link preservation -## + SSH Tool +### + SSH Tool Remote command execution with persistent connections: @@ -278,11 +256,11 @@ Remote command execution with persistent connections: - **SSHFS mounts**: Optional automatic mounting of remote directories - **Compat mode**: Windows host support with automatic shell probing -## + Browser Tool (Puppeteer with Stealth) +### + Browser Tool (Puppeteer with Stealth) Headless browser automation with 14 stealth scripts to evade bot detection: -- **25+ actions**: Navigate, click, type, fill, scroll, drag, screenshot, evaluate JS, extract readable content +- **Automation actions**: Navigate, click, type, fill, scroll, drag, screenshot, evaluate JS, and extract readable content - **Accessibility snapshots**: Observe interactive elements via the accessibility tree with numeric IDs for reliable targeting - **14 stealth plugins**: Custom scripts covering toString tampering, WebGL fingerprinting, audio context, screen dimensions, font enumeration, plugin/mime-type mocking, hardware concurrency, codec availability, iframe detection, locale spoofing, worker detection, and more - **User agent spoofing**: Removes `HeadlessChrome` identifier, generates proper Client Hints brand lists, applies overrides via CDP Network and Emulation domains @@ -290,7 +268,7 @@ Headless browser automation with 14 stealth scripts to evade bot detection: - **Reader mode**: `extract_readable` action uses Mozilla Readability for clean article extraction - **Headless/visible toggle**: Switch modes at runtime via `/browser` command or `browser.headless` setting -## + Cursor Provider +### + Cursor Provider Use your Cursor Pro subscription for AI completions: @@ -299,7 +277,7 @@ Use your Cursor Pro subscription for AI completions: - **Conversation caching**: Persists context across requests in the same session - **Shell streaming**: Real-time stdout/stderr during command execution -## + Multi-Credential Support +### + Multi-Credential Support Distribute load across multiple API keys: @@ -308,7 +286,7 @@ Distribute load across multiple API keys: - **Automatic fallback**: Switches credentials mid-session when rate limits are hit - **Consistent hashing**: FNV-1a hashing ensures stable credential assignment per session -## + Image Generation +### + Image Generation Create images directly from the agent: @@ -317,7 +295,7 @@ Create images directly from the agent: - **Inline display**: Images render in terminals supporting Kitty/iTerm2 graphics - Saves to temp files and reports paths for further manipulation -## + TUI Overhaul +### + TUI Overhaul Modern terminal interface with smart session management: @@ -330,15 +308,19 @@ Modern terminal interface with smart session management: - **Grouped tool display**: Consecutive Read calls shown in compact tree view - **Emergency terminal restore**: Crash handlers prevent terminal corruption -## + Edit Fuzzy Matching +### + Hashline Edits -Handles whitespace and indentation variance automatically: +Hashline gives every line a short content-hash anchor. The model references anchors instead of reproducing text — no whitespace reproduction, no "string not found", no ambiguous matches. If the file changed since the last read, hashes won't match and the edit is rejected before anything gets corrupted. -- High-confidence fuzzy matching for `oldText` in edit operations -- Fixes the #1 pain point: edits failing due to invisible whitespace differences -- Configurable via `edit.fuzzyMatch` setting (enabled by default) +Benchmarked across 16 models, 180 tasks, 3 runs each: -## + Native Engine (Rust N-API) +- **Grok Code Fast 1**: 6.7% → 68.3% — a _tenfold_ improvement hidden behind mechanical patch failures +- **Gemini 3 Flash**: +5pp over `str_replace`, beating Google's own best attempt +- **Grok 4 Fast**: 61% fewer output tokens — stopped burning context on retry loops +- **MiniMax**: more than doubled success rate +- Matches or beats `str_replace` for nearly every model tested; weakest models gain the most + +### + Native Engine (Rust N-API) ~7,500 lines of Rust compiled to a platform-tagged N-API addon, providing performance-critical operations without shelling out to external commands: @@ -360,7 +342,7 @@ Handles whitespace and indentation variance automatically: Supported platforms: `linux-x64`, `linux-arm64`, `darwin-x64`, `darwin-arm64`, `win32-x64`. -## ... and many more +### ... and many more - **`omp config` subcommand**: Manage settings from CLI (`list`, `get`, `set`, `reset`, `path`) - **`omp setup` subcommand**: Install optional dependencies (e.g., `omp setup python` for Jupyter kernel) @@ -379,27 +361,887 @@ Supported platforms: `linux-x64`, `linux-arm64`, `darwin-x64`, `darwin-arm64`, ` --- -## Packages +## Installation -| Package | Description | -| ------------------------------------------------------ | -------------------------------------------------------------------------------------- | -| **[@oh-my-pi/pi-ai](packages/ai)** | Multi-provider LLM client (Anthropic, OpenAI, Gemini, Bedrock, Cursor, Codex, Copilot) | -| **[@oh-my-pi/pi-agent-core](packages/agent)** | Agent runtime with tool calling and state management | -| **[@oh-my-pi/pi-coding-agent](packages/coding-agent)** | Interactive coding agent CLI | -| **[@oh-my-pi/pi-tui](packages/tui)** | Terminal UI library with differential rendering | -| **[@oh-my-pi/pi-natives](packages/natives)** | N-API bindings for grep, shell, image, text, syntax highlighting, and more | -| **[@oh-my-pi/omp-stats](packages/stats)** | Local observability dashboard for AI usage statistics | +### Via Bun (recommended) + +Requires [Bun](https://bun.sh) **>= 1.3.7**: + +```bash +bun install -g @oh-my-pi/pi-coding-agent +``` + +### Via installer script + +**Linux / macOS:** + +```bash +curl -fsSL https://raw.githubusercontent.com/can1357/oh-my-pi/main/scripts/install.sh | sh +``` + +**Windows (PowerShell):** + +```powershell +irm https://raw.githubusercontent.com/can1357/oh-my-pi/main/scripts/install.ps1 | iex +``` + +By default, the installer uses Bun when available (and compatible), otherwise installs the prebuilt binary. + +Options: + +- POSIX (`install.sh`): `--source`, `--binary`, `--ref `, `-r ` +- PowerShell (`install.ps1`): `-Source`, `-Binary`, `-Ref ` +- `--ref`/`-Ref` with binary mode must reference a release tag; branch/commit refs require source mode + +Set custom install directory with `PI_INSTALL_DIR`. + +Examples: + +```bash +# Source install (Bun) +curl -fsSL https://raw.githubusercontent.com/can1357/oh-my-pi/main/scripts/install.sh | sh -s -- --source + +# Install release tag via binary +curl -fsSL https://raw.githubusercontent.com/can1357/oh-my-pi/main/scripts/install.sh | sh -s -- --binary --ref v3.20.1 + +# Install branch/commit via source +curl -fsSL https://raw.githubusercontent.com/can1357/oh-my-pi/main/scripts/install.sh | sh -s -- --source --ref main +``` + +```powershell +# Install release tag via binary +& ([scriptblock]::Create((irm https://raw.githubusercontent.com/can1357/oh-my-pi/main/scripts/install.ps1))) -Binary -Ref v3.20.1 +# Install branch/commit via source +& ([scriptblock]::Create((irm https://raw.githubusercontent.com/can1357/oh-my-pi/main/scripts/install.ps1))) -Source -Ref main +``` + +### Via [mise](https://mise.jdx.dev) + +```bash +mise use -g github:can1357/oh-my-pi +``` + +### Manual download + +Download binaries directly from [GitHub Releases](https://github.com/can1357/oh-my-pi/releases/latest). + +--- + +## Getting Started + +### Terminal Setup + +Pi uses the [Kitty keyboard protocol](https://sw.kovidgoyal.net/kitty/keyboard-protocol/) for reliable modifier key detection. Most modern terminals support this protocol, but some require configuration. + +**Kitty, iTerm2:** Work out of the box. + +**Ghostty:** Add to your Ghostty config (`~/.config/ghostty/config`): + +``` +keybind = alt+backspace=text:\x1b\x7f +keybind = shift+enter=text:\n +``` + +**wezterm:** Create `~/.wezterm.lua`: + +```lua +local wezterm = require 'wezterm' +local config = wezterm.config_builder() +config.enable_kitty_keyboard = true +return config +``` + +**Windows Terminal:** Does not support the Kitty keyboard protocol. Shift+Enter cannot be distinguished from Enter. Use Ctrl+Enter for multi-line input instead. All other keybindings work correctly. + +### API Keys & OAuth + +**Option 1: Environment variables** (common examples) + +| Provider | Environment Variable | +| ---------- | -------------------- | +| Anthropic | `ANTHROPIC_API_KEY` | +| OpenAI | `OPENAI_API_KEY` | +| Google | `GEMINI_API_KEY` | +| Mistral | `MISTRAL_API_KEY` | +| Groq | `GROQ_API_KEY` | +| Cerebras | `CEREBRAS_API_KEY` | +| xAI | `XAI_API_KEY` | +| OpenRouter | `OPENROUTER_API_KEY` | +| Z.AI | `ZAI_API_KEY` | + +See [Environment Variables](packages/coding-agent/docs/environment-variables.md) for the full list. + +**Option 2: OAuth / interactive auth (`/login`)** + +Use `/login` to authenticate with supported providers: + +- Anthropic (Claude Pro/Max) +- ChatGPT Plus/Pro (Codex) +- GitHub Copilot +- Google Cloud Code Assist (Gemini CLI) +- Antigravity (Gemini 3, Claude, GPT-OSS) +- Cursor +- Kimi Code +- Perplexity +- OpenCode Zen +- Z.AI (GLM Coding Plan) +- MiniMax Coding Plan (International / China) + +```bash +omp +/login +``` + +**Credential behavior:** + +- `/login` appends credentials for the provider (it does not wipe existing entries) +- `/logout` clears saved credentials for the selected provider +- Credentials are stored in `~/.omp/agent/agent.db` +- For the same provider, saved API key credentials are selected before OAuth credentials + +### First 15 Minutes (Recommended) + +This is the practical onboarding flow for new users. + +#### 1) Set up providers + +- **API keys** (fastest): export `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`, etc. +- **OAuth subscriptions**: run `/login` and authenticate with your provider account + +#### 2) Configure model roles via `/model` + +Use `/model` in the TUI and assign role models: + +- `default` → normal implementation work +- `smol` → fast/cheap exploration and lightweight tasks +- `slow` → deep reasoning for complex debugging/refactors +- `plan` → model used while plan mode is active (`/plan`) +- `commit` → model used by commit/changelog workflows + +This setup is interactive and persisted for you. + +#### 3) Use `/plan` before making large changes + +`/plan` toggles plan mode. Use it when you want architecture and execution sequencing before edits. + +Typical flow: + +1. Run `/plan` +2. Ask for a concrete implementation plan +3. Refine the plan +4. Approve and execute + +#### 4) Review context via `/extensions` + +If context usage is unexpectedly high, inspect discovered external provider assets (rules/prompts/context/hooks/extensions). + +Run `/extensions` and: + +- Browse provider tabs (`Tab` / `Shift+Tab`) +- Inspect each item source (`via ` + file path) +- Disable full providers or specific items you don't want (`Space`) + +--- + +## Usage + +### Slash Commands + +These are **in-chat slash commands** (not CLI subcommands). +| Command | Description | +| ------- | ----------- | +| `/settings` | Open settings menu | +| `/plan` | Toggle plan mode | +| `/model` (`/models`) | Open model selector | +| `/export [path]` | Export session to HTML | +| `/dump` | Copy session transcript to clipboard | +| `/share` | Upload session as a secret gist | +| `/session` | Show session info and usage | +| `/usage` | Show provider usage and limits | +| `/hotkeys` | Show keyboard shortcuts | +| `/extensions` (`/status`) | Open Extension Control Center | +| `/changelog` | Show changelog entries | +| `/tree` | Navigate session tree | +| `/branch` | Open branch selector (tree or message selector, based on settings) | +| `/fork` | Fork from a previous message | +| `/resume` | Open session picker | +| `/new` | Start a new session | +| `/compact [focus]` | Compact context manually | +| `/handoff [focus]` | Hand off context to a new session | +| `/browser [headless\|visible]` | Toggle browser mode | +| `/mcp ...` | Manage MCP servers | +| `/memory ...` | Inspect/clear/rebuild memory state | +| `/move ` | Move current session to a different cwd | +| `/background` (`/bg`) | Detach UI and continue in background | +| `/debug` | Open debug tools | +| `/copy` | Copy last agent message | +| `/login` / `/logout` | OAuth login/logout | +| `/exit` (`/quit`) | Exit interactive mode | + +Bundled custom slash commands include `/review` (interactive code review launcher). + +### Editor Features + +**File reference (`@`):** Type `@` to fuzzy-search project files. Respects `.gitignore`. + +**Path completion (Tab):** Complete relative paths, `../`, `~/`, etc. + +**Drag & drop:** Drag files from your file manager into the terminal. + +**Multi-line paste:** Pasted content is collapsed in preview but sent in full. + +**Message queuing:** Submit messages while the agent is working; queue behavior is configurable in `/settings`. + +### Keyboard Shortcuts + +**Navigation:** + +| Key | Action | +| ------------------------ | -------------------------------------------- | +| Arrow keys | Move cursor / browse history (Up when empty) | +| Option+Left/Right | Move by word | +| Ctrl+A / Home / Cmd+Left | Start of line | +| Ctrl+E / End / Cmd+Right | End of line | + +**Editing:** + +| Key | Action | +| ------------------------- | ----------------------- | +| Enter | Send message | +| Shift+Enter / Alt+Enter | New line | +| Ctrl+W / Option+Backspace | Delete word backwards | +| Ctrl+U | Delete to start of line | +| Ctrl+K | Delete to end of line | + +**Other:** + +| Key | Action | +| --------------------- | --------------------------------------------------------- | +| Tab | Path completion / accept autocomplete | +| Escape | Cancel autocomplete / abort streaming | +| Ctrl+C | Clear editor (first) / exit (second) | +| Ctrl+D | Exit (when editor is empty) | +| Ctrl+Z | Suspend to background (use `fg` in shell to resume) | +| Shift+Tab | Cycle thinking level | +| Ctrl+P / Shift+Ctrl+P | Cycle role models (slow/default/smol), temporary on shift | +| Alt+P | Select model temporarily | +| Ctrl+L | Open model selector | +| Alt+Shift+P | Toggle plan mode | +| Ctrl+R | Search prompt history | +| Ctrl+O | Toggle tool output expansion | +| Ctrl+T | Toggle todo list expansion | +| Ctrl+G | Edit message in external editor (`$VISUAL` or `$EDITOR`) | +| Alt+H | Toggle speech-to-text recording | + +### Bash Mode + +Prefix commands with `!` to execute them and include output in context: + +```bash +!git status +!ls -la +``` + +Use `!!` to execute but **exclude output from LLM context**: + +```bash +!!git status +``` + +Output streams in real-time. Press Escape to cancel. + +### Image Support + +**Attach images by reference:** + +```text +What's in @/path/to/image.png? +``` + +Or paste/drop images directly (`Ctrl+V` or drag-and-drop). + +Supported formats: `.jpg`, `.jpeg`, `.png`, `.gif`, `.webp` + +Toggle inline images via `/settings` or set `terminal.showImages: false`. + +--- + +## Sessions + +Sessions are stored as JSONL with a tree structure for branching and replay. + +See [packages/coding-agent/docs/session.md](packages/coding-agent/docs/session.md) for the file format and API. + +### Session Management + +Sessions auto-save to `~/.omp/agent/sessions/` (grouped by working directory). + +```bash +omp --continue # Continue most recent session +omp -c + +omp --resume # Open session picker +omp -r + +omp --resume # Resume by session ID prefix +omp --resume # Resume by explicit .jsonl path +omp --session # Alias of --resume +omp --no-session # Ephemeral mode (don't save) +``` + +Session IDs are Snowflake-style hex IDs (not UUIDs). + +### Context Compaction + +Long sessions can exhaust context windows. Compaction summarizes older messages while keeping recent context. + +**Manual:** `/compact` or `/compact Focus on the API changes` + +**Automatic:** Enable via `/settings`. + +- **Overflow recovery**: model returns context overflow; compact and retry. +- **Threshold maintenance**: context exceeds configured headroom after a successful turn. + +**Configuration** (`~/.omp/agent/config.yml`): + +```yaml +compaction: + enabled: true + reserveTokens: 16384 + keepRecentTokens: 20000 + autoContinue: true +``` + +See [packages/coding-agent/docs/compaction.md](packages/coding-agent/docs/compaction.md) for internals and hook integration. + +### Branching + +**In-place navigation (`/tree`):** Navigate the session tree without creating new files. + +- Search by typing, page with ←/→ +- Filter modes (`Ctrl+O`): default → no-tools → user-only → labeled-only → all +- Press `Shift+L` to label entries as bookmarks + +**Create new session (`/branch` / `/fork`):** Branch to a new session file from a selected previous message. + +--- + +## Configuration + +### Project Context Files + +omp discovers project context from supported config directories (for example `.omp`, `.claude`, `.codex`, `.gemini`). + +Common files: + +- `AGENTS.md` +- `CLAUDE.md` + +Use these for: + +- Project instructions and guardrails +- Common commands and workflows +- Architecture documentation +- Coding/testing conventions + +### Custom System Prompt + +Replace the default system prompt by creating `SYSTEM.md`: + +1. **Project-local:** `.omp/SYSTEM.md` (takes precedence) +2. **Global:** `~/.omp/agent/SYSTEM.md` (fallback) + `--system-prompt` overrides both files. Use `--append-system-prompt` to append additional instructions. + +### Custom Models and Providers + +Add custom providers/models via `~/.omp/agent/models.yml`. + +`models.json` is still supported for legacy configs, but `models.yml` is the modern format. + +> See [models.yml provider integration guide](packages/coding-agent/docs/models.md) for schema and merge behavior. + +```yaml +providers: + ollama: + baseUrl: http://localhost:11434/v1 + apiKey: OLLAMA_API_KEY + api: openai-completions + models: + - id: llama-3.1-8b + name: Llama 3.1 8B (Local) + reasoning: false + input: [text] + cost: + input: 0 + output: 0 + cacheRead: 0 + cacheWrite: 0 + contextWindow: 128000 + maxTokens: 32000 +``` + +**Supported APIs:** `openai-completions`, `openai-responses`, `openai-codex-responses`, `azure-openai-responses`, `anthropic-messages`, `google-generative-ai`, `google-vertex` + +### Settings File + +Global settings are stored in: + +- `~/.omp/agent/config.yml` + +Project overrides are loaded from discovered project settings files (commonly `.omp/settings.json`). + +Global `config.yml` example: + +```yaml +theme: + dark: titanium + light: light + +modelRoles: + default: anthropic/claude-sonnet-4-20250514 + +defaultThinkingLevel: medium +enabledModels: + - anthropic/* + - "*gpt*" + - gemini-2.5-pro:high + +steeringMode: one-at-a-time +followUpMode: one-at-a-time +interruptMode: immediate + +shellPath: C:\\path\\to\\bash.exe +hideThinkingBlock: false +collapseChangelog: false + +disabledProviders: [] +disabledExtensions: [] + +compaction: + enabled: true + reserveTokens: 16384 + keepRecentTokens: 20000 + +skills: + enabled: true + +retry: + enabled: true + maxRetries: 3 + baseDelayMs: 2000 + +terminal: + showImages: true +``` + +Legacy migration notes: + +- `settings.json` → `config.yml` +- `queueMode` → `steeringMode` +- flat `theme: "..."` → `theme.dark` / `theme.light` + +--- + +## Extensions + +### Themes + +Built-in themes include `dark`, `light`, and many bundled variants. + +Select theme via `/settings` or set in `~/.omp/agent/config.yml`: + +```yaml +theme: + dark: titanium + light: light +``` + +**Custom themes:** create `~/.omp/agent/themes/*.json`. + +> See [Theme Documentation](packages/coding-agent/docs/theme.md). + +### Custom Slash Commands + +Define reusable prompt commands as Markdown files: + +- Global: `~/.omp/agent/commands/*.md` +- Project: `.omp/commands/*.md` + +```markdown +--- +description: Review staged git changes +--- + +Review the staged changes (`git diff --cached`). Focus on: + +- Bugs and logic errors +- Security issues +- Error handling gaps +``` + +Filename (without `.md`) becomes the command name. + +Argument placeholders: + +- `$1`, `$2`, ... positional arguments +- `$@` and `$ARGUMENTS` for all arguments joined + +TypeScript custom commands are also supported: + +- `~/.omp/agent/commands//index.ts` +- `.omp/commands//index.ts` + +Bundled TypeScript command: `/review`. + +### Skills + +Skills are capability packages loaded on-demand. + +Common locations: + +- `~/.omp/agent/skills/*/SKILL.md` +- `.omp/skills/*/SKILL.md` +- `~/.claude/skills/*/SKILL.md`, `.claude/skills/*/SKILL.md` +- `~/.codex/skills/*/SKILL.md`, `.codex/skills/*/SKILL.md` + +```markdown +--- +name: brave-search +description: Web search via Brave Search API. +--- + +# Brave Search +``` + +`description` drives matching; `name` defaults to the folder name when omitted. + +Disable skills with `omp --no-skills` or `skills.enabled: false`. + +> See [Skills Documentation](packages/coding-agent/docs/skills.md). + +### Hooks + +Hooks are TypeScript modules that subscribe to lifecycle events. + +Hook locations: + +- Global: `~/.omp/agent/hooks/pre/*.ts`, `~/.omp/agent/hooks/post/*.ts` +- Project: `.omp/hooks/pre/*.ts`, `.omp/hooks/post/*.ts` +- CLI: `--hook ` + +```typescript +import type { HookAPI } from "@oh-my-pi/pi-coding-agent/hooks"; + +export default function (omp: HookAPI) { + omp.on("tool_call", async (event, ctx) => { + if (event.toolName === "bash" && /sudo/.test(event.input.command as string)) { + const ok = await ctx.ui.confirm("Allow sudo?", event.input.command as string); + if (!ok) return { block: true, reason: "Blocked by user" }; + } + return undefined; + }); +} +``` + +Inject messages from hooks with: + +```ts +omp.sendMessage(message, { triggerTurn: true }); +``` + +> See [Hooks Documentation](packages/coding-agent/docs/hooks.md) and [examples/hooks/](packages/coding-agent/examples/hooks/). + +### Custom Tools + +Custom tools extend the built-in toolset and are callable by the model. + +Auto-discovered locations: + +- Global: `~/.omp/agent/tools/*/index.ts` +- Project: `.omp/tools/*/index.ts` + +```typescript +import { Type } from "@sinclair/typebox"; +import type { CustomToolFactory } from "@oh-my-pi/pi-coding-agent"; +const factory: CustomToolFactory = () => ({ + name: "greet", + label: "Greeting", + description: "Generate a greeting", + parameters: Type.Object({ + name: Type.String({ description: "Name to greet" }), + }), + async execute(_toolCallId, params) { + const { name } = params as { name: string }; + return { content: [{ type: "text", text: `Hello, ${name}!` }] }; + }, +}); +export default factory; +``` + +> See [Custom Tools Documentation](packages/coding-agent/docs/custom-tools.md) and [examples/custom-tools/](packages/coding-agent/examples/custom-tools/). + +--- + +## CLI Reference + +```bash +omp [options] [@files...] [messages...] +omp [args] [flags] +``` + +### Options + +| Option | Description | +| ------------------------------------- | ------------------------------------------------------------------ | +| `--provider ` | Provider hint (legacy; prefer `--model`) | +| `--model ` | Model ID (supports fuzzy match) | +| `--smol ` | Override the `smol` role model for this run | +| `--slow ` | Override the `slow` role model for this run | +| `--plan ` | Override the `plan` role model for this run | +| `--models ` | Comma-separated model patterns for role cycling | +| `--list-models [pattern]` | List available models (optional fuzzy filter) | +| `--thinking ` | Thinking level: `off`, `minimal`, `low`, `medium`, `high`, `xhigh` | +| `--api-key ` | API key (overrides environment/provider lookup) | +| `--system-prompt ` | Replace system prompt | +| `--append-system-prompt ` | Append to system prompt | +| `--mode ` | Output mode: `text`, `json`, `rpc` | +| `--print`, `-p` | Non-interactive: process prompt and exit | +| `--continue`, `-c` | Continue most recent session | +| `--resume`, `-r [id\|path]` | Resume by ID prefix/path (or open picker if omitted) | +| `--session ` | Alias of `--resume` | +| `--session-dir ` | Directory for session storage and lookup | +| `--no-session` | Don't save session | +| `--tools ` | Restrict to comma-separated built-in tool names | +| `--no-tools` | Disable all built-in tools | +| `--no-lsp` | Disable LSP integration | +| `--no-pty` | Disable PTY-based interactive bash execution | +| `--extension `, `-e` | Load extension file (repeatable) | +| `--hook ` | Load hook/extension file (repeatable) | +| `--no-extensions` | Disable extension discovery (`-e` paths still load) | +| `--no-skills` | Disable skills discovery and loading | +| `--skills ` | Comma-separated glob patterns to filter skills | +| `--allow-home` | Allow starting from home dir without auto-chdir | +| `--no-title` | Disable automatic session title generation | +| `--export [output]` | Export session to HTML | +| `--help`, `-h` | Show help | +| `--version`, `-v` | Show version | + +### Subcommands + +`omp` also ships dedicated subcommands: + +- `commit` +- `config` +- `grep` +- `jupyter` +- `plugin` +- `search` (alias: `q`) +- `setup` +- `shell` +- `stats` +- `update` + +### File Arguments + +Include files with `@` prefix: + +```bash +omp @prompt.md "Answer this" +omp @screenshot.png "What's in this image?" +omp @requirements.md @design.png "Implement this" +``` + +Text files are wrapped in `` blocks. Images are attached. + +### Examples + +```bash +# Interactive mode +omp +# Non-interactive +omp -p "List all .ts files in src/" +omp -c "What did we discuss?" +# Resume by ID prefix +omp -r abc123 + +# Model cycling with patterns +omp --models "sonnet:high,haiku:low" + +# Restrict toolset for read-only review +omp --tools read,grep,find -p "Review the architecture" +# Export session +omp --export session.jsonl output.html +``` + +### Environment Variables + +| Variable | Description | +| ------------------------------------------------- | ------------------------------------------------------- | +| `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, etc. | Provider credentials | +| `PI_CODING_AGENT_DIR` | Override agent data directory (default: `~/.omp/agent`) | +| `PI_PACKAGE_DIR` | Override package directory resolution | +| `PI_SMOL_MODEL`, `PI_SLOW_MODEL`, `PI_PLAN_MODEL` | Role-model overrides | +| `PI_NO_PTY` | Disable PTY-based bash execution | +| `VISUAL`, `EDITOR` | External editor for Ctrl+G | + +See [Environment Variables](packages/coding-agent/docs/environment-variables.md) for the complete reference. + +--- + +## Tools + +Use `--tools ` to restrict available built-in tools. + +### Built-in Tool Names (`--tools`) + +| Tool | Description | +| ------------ | -------------------------------------------------------------- | +| `ask` | Ask the user structured follow-up questions (interactive mode) | +| `bash` | Execute shell commands | +| `python` | Execute Python code in IPython kernel | +| `calc` | Deterministic calculator/evaluator | +| `ssh` | Execute commands on configured SSH hosts | +| `edit` | In-place file editing (hashline/patch/replace modes) | +| `find` | Find files by glob pattern | +| `grep` | Search file content | +| `lsp` | Language server actions | +| `notebook` | Edit Jupyter notebooks | +| `read` | Read files/directories (default text cap: 3000 lines) | +| `browser` | Browser automation tool (model-facing name: `puppeteer`) | +| `task` | Launch subagents | +| `todo_write` | Track task progress | +| `fetch` | Fetch and extract URL content | +| `web_search` | Search the web | +| `write` | Create/overwrite files | + +Notes: + +- Some tools are setting-gated (`calc`, `browser`, etc.) +- `ask` requires interactive UI +- `ssh` requires configured SSH hosts + +Example: + +`omp --tools read,grep,find -p "Review this codebase"` + +For adding new tools, see [Custom Tools](#custom-tools). + +--- + +## Programmatic Usage + +### SDK + +For embedding omp in Node.js/TypeScript applications, use the SDK: + +```typescript +import { ModelRegistry, SessionManager, createAgentSession, discoverAuthStorage } from "@oh-my-pi/pi-coding-agent"; +const authStorage = await discoverAuthStorage(); +const modelRegistry = new ModelRegistry(authStorage); +await modelRegistry.refresh(); +const { session } = await createAgentSession({ + sessionManager: SessionManager.inMemory(), + authStorage, + modelRegistry, +}); +session.subscribe((event) => { + if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") { + process.stdout.write(event.assistantMessageEvent.delta); + } +}); +await session.prompt("What files are in the current directory?"); +``` + +The SDK provides control over: + +- Model selection and thinking level +- System prompt (replace or append) +- Built-in/custom tools +- Hooks, skills, context files, slash commands +- Session persistence (`SessionManager`) +- Settings (`Settings`) +- API key and OAuth resolution + +> See [SDK Documentation](packages/coding-agent/docs/sdk.md) and [examples/sdk/](packages/coding-agent/examples/sdk/). + +### RPC Mode + +For embedding from other languages or process isolation: + +```bash +omp --mode rpc --no-session +``` + +Send JSON commands on stdin: + +```json +{"id":"req-1","type":"prompt","message":"List all .ts files"} +{"id":"req-2","type":"abort"} +``` + +Responses are emitted as `type: "response"`; session events stream on stdout as they occur. + +> See [RPC Documentation](packages/coding-agent/docs/rpc.md) for the full protocol. + +### HTML Export + +```bash +omp --export session.jsonl # Auto-generated filename +omp --export session.jsonl output.html # Custom filename +``` + +Works with session files and JSON event logs from `--mode json`. + +--- + +## Philosophy + +omp is a fork of [pi-mono](https://github.com/badlogic/pi-mono) by [Mario Zechner](https://github.com/mariozechner), extended with a batteries-included coding workflow. + +Key ideas: + +- Keep interactive terminal-first UX for real coding work +- Include practical built-ins (tools, sessions, branching, subagents, extensibility) +- Make advanced behavior configurable rather than hidden + +--- + +## Development + +### Debug Command + +`/debug` opens tools for debugging, reporting, and profiling. + +For architecture and contribution guidelines, see [packages/coding-agent/DEVELOPMENT.md](packages/coding-agent/DEVELOPMENT.md). + +--- + +## Monorepo Packages + +| Package | Description | +| --------------------------------------------------------- | -------------------------------------------------------------------------- | +| **[@oh-my-pi/pi-ai](packages/ai)** | Multi-provider LLM client with streaming and model/provider integration | +| **[@oh-my-pi/pi-agent-core](packages/agent)** | Agent runtime with tool calling and state management | +| **[@oh-my-pi/pi-coding-agent](packages/coding-agent)** | Interactive coding agent CLI and SDK | +| **[@oh-my-pi/pi-tui](packages/tui)** | Terminal UI library with differential rendering | +| **[@oh-my-pi/pi-natives](packages/natives)** | N-API bindings for grep, shell, image, text, syntax highlighting, and more | +| **[@oh-my-pi/omp-stats](packages/stats)** | Local observability dashboard for AI usage statistics | +| **[@oh-my-pi/pi-utils](packages/utils)** | Shared utilities (logging, streams, dirs/env/process helpers) | +| **[@oh-my-pi/swarm-extension](packages/swarm-extension)** | Swarm orchestration extension package | ### Rust Crates -| Crate | Description | -| ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | -| **[pi-natives](crates/pi-natives)** | N-API native addon — 13 modules, ~7,500 lines of Rust (see [feature section](#-native-performance-engine-rust-n-api) above) | -| **[brush-core-vendored](crates/brush-core-vendored)** | Vendored fork of [brush-shell](https://github.com/reubeno/brush) for embedded bash execution | -| **[brush-builtins-vendored](crates/brush-builtins-vendored)** | Vendored bash builtins (cd, echo, test, printf, read, export, etc.) | +| Crate | Description | +| ------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | +| **[pi-natives](crates/pi-natives)** | Core Rust native addon used by `@oh-my-pi/pi-natives` | +| **[brush-core-vendored](crates/brush-core-vendored)** | Vendored fork of [brush-shell](https://github.com/reubeno/brush) for embedded bash execution | +| **[brush-builtins-vendored](crates/brush-builtins-vendored)** | Vendored bash builtins (cd, echo, test, printf, read, export, etc.) | --- ## License -MIT - Original work copyright Mario Zechner +MIT. See [LICENSE](LICENSE). + +Copyright (c) 2025 Mario Zechner +Copyright (c) 2025-2026 Can Bölük diff --git a/packages/coding-agent/README.md b/packages/coding-agent/README.md index 1b884c944..5f181e5da 100644 --- a/packages/coding-agent/README.md +++ b/packages/coding-agent/README.md @@ -1,1055 +1,12 @@ -# omp +# @oh-my-pi/pi-coding-agent -A terminal-based coding agent with multi-model support, mid-session model switching, and a simple CLI for headless coding tasks. +Core implementation package for the `omp` coding agent in the `oh-my-pi` monorepo. -Works on Linux, macOS, and Windows (requires bash; see [Windows Setup](#windows-setup)). +For installation, setup, provider configuration, model roles, slash commands, and full CLI reference, see: +- [Monorepo README (local)](../../README.md) +- [Monorepo README (GitHub)](https://github.com/can1357/oh-my-pi#readme) -## Table of Contents - -- [Getting Started](#getting-started) - - [Installation](#installation) - - [Windows Setup](#windows-setup) - - [Terminal Setup](#terminal-setup) - - [API Keys & OAuth](#api-keys--oauth) - - [Quick Start](#quick-start) -- [Usage](#usage) - - [Slash Commands](#slash-commands) - - [Editor Features](#editor-features) - - [Keyboard Shortcuts](#keyboard-shortcuts) - - [Bash Mode](#bash-mode) - - [Image Support](#image-support) -- [Sessions](#sessions) - - [Session Management](#session-management) - - [Context Compaction](#context-compaction) - - [Branching](#branching) -- [Configuration](#configuration) - - [Project Context Files](#project-context-files) - - [Custom System Prompt](#custom-system-prompt) - - [Custom Models and Providers](#custom-models-and-providers) - - [Settings File](#settings-file) -- [Extensions](#extensions) - - [Themes](#themes) - - [Custom Slash Commands](#custom-slash-commands) - - [Skills](#skills) - - [Hooks](#hooks) - - [Custom Tools](#custom-tools) -- [CLI Reference](#cli-reference) -- [Tools](#tools) -- [Programmatic Usage](#programmatic-usage) - - [SDK](#sdk) - - [RPC Mode](#rpc-mode) - - [HTML Export](#html-export) -- [Philosophy](#philosophy) -- [Development](#development) -- [License](#license) - ---- - -## Getting Started - -### Installation - -**npm (recommended):** - -```bash -npm install -g @oh-my-pi/pi-coding-agent -``` - -**Standalone binary:** - -Download from [GitHub Releases](https://github.com/can1357/oh-my-pi/releases): - -| Platform | Binary | -| ------------------- | --------------------- | -| macOS Apple Silicon | `omp-darwin-arm64` | -| macOS Intel | `omp-darwin-x64` | -| Linux x64 | `omp-linux-x64` | -| Linux ARM64 | `omp-linux-arm64` | -| Windows x64 | `omp-windows-x64.exe` | - -```bash -# macOS/Linux -chmod +x omp-darwin-arm64 -./omp-darwin-arm64 - -# Windows -omp-windows-x64.exe -``` - -**macOS note:** The binary is unsigned. If blocked, run: `xattr -c ./omp` - -**Build from source** (requires [Bun](https://bun.sh) 1.0+): - -```bash -git clone https://github.com/can1357/oh-my-pi.git -cd pi-mono && npm install -cd packages/coding-agent && npm run build:binary -./dist/omp -``` - -### Windows Setup - -Omp requires a bash shell on Windows. Checked locations (in order): - -1. Custom path from `~/.omp/agent/settings.json` -2. Git Bash (`C:\Program Files\Git\bin\bash.exe`) -3. `bash.exe` on PATH (Cygwin, MSYS2, WSL) - -For most users, [Git for Windows](https://git-scm.com/download/win) is sufficient. - -**Custom shell path:** - -```json -// ~/.omp/agent/settings.json -{ - "shellPath": "C:\\cygwin64\\bin\\bash.exe" -} -``` - -### Terminal Setup - -Pi uses the [Kitty keyboard protocol](https://sw.kovidgoyal.net/kitty/keyboard-protocol/) for reliable modifier key detection. Most modern terminals support this protocol, but some require configuration. - -**Kitty, iTerm2:** Work out of the box. - -**Ghostty:** Add to your Ghostty config (`~/.config/ghostty/config`): - -``` -keybind = alt+backspace=text:\x1b\x7f -keybind = shift+enter=text:\n -``` - -**wezterm:** Create `~/.wezterm.lua`: - -```lua -local wezterm = require 'wezterm' -local config = wezterm.config_builder() -config.enable_kitty_keyboard = true -return config -``` - -**Windows Terminal:** Does not support the Kitty keyboard protocol. Shift+Enter cannot be distinguished from Enter. Use Ctrl+Enter for multi-line input instead. All other keybindings work correctly. - -### API Keys & OAuth - -**Option 1: Environment variables** (recommended) - -| Provider | Auth Key | Environment Variable | -| ---------- | ------------ | -------------------- | -| Anthropic | `anthropic` | `ANTHROPIC_API_KEY` | -| OpenAI | `openai` | `OPENAI_API_KEY` | -| Google | `google` | `GEMINI_API_KEY` | -| Mistral | `mistral` | `MISTRAL_API_KEY` | -| Groq | `groq` | `GROQ_API_KEY` | -| Cerebras | `cerebras` | `CEREBRAS_API_KEY` | -| xAI | `xai` | `XAI_API_KEY` | -| OpenRouter | `openrouter` | `OPENROUTER_API_KEY` | -| ZAI | `zai` | `ZAI_API_KEY` | - -**Option 2: OAuth** - -Use `/login` to authenticate with subscription-based or free-tier providers: - -| Provider | Models | Cost | -| -------------------------- | ----------------------------------------------- | --------------------- | -| Anthropic (Claude Pro/Max) | Claude models via your subscription | Subscription | -| Cursor | Claude, GPT-4o via Cursor Pro subscription | Subscription | -| GitHub Copilot | GPT-4o, Claude, Gemini via Copilot subscription | Subscription | -| OpenAI Codex | o3, o4-mini via ChatGPT Plus/Pro subscription | Subscription | -| Google Gemini CLI | Gemini 2.0/2.5 models | Free (Google account) | -| Google Antigravity | Gemini 3, Claude, GPT-OSS | Free (Google account) | - -```bash -omp -/login # Select provider, authorize in browser -``` - -**Note:** `/login` replaces any existing API keys for that provider with OAuth credentials. If OAuth credentials already exist, `/login` appends another entry. - -**GitHub Copilot notes:** - -- Press Enter for github.com, or enter your GitHub Enterprise Server domain -- If you get "model not supported" error, enable it in VS Code: Copilot Chat → model selector → select model → "Enable" - -**Google providers notes:** - -- Gemini CLI uses the production Cloud Code Assist endpoint (standard Gemini models) -- Antigravity uses a sandbox endpoint with access to Gemini 3, Claude (sonnet/opus thinking), and GPT-OSS models -- Both are free with any Google account, subject to rate limits -- Paid Cloud Code Assist subscriptions: set `GOOGLE_CLOUD_PROJECT` or `GOOGLE_CLOUD_PROJECT_ID` env var to your project ID - -Credentials stored in `~/.omp/agent/agent.db`. Use `/logout` to clear. - -### Quick Start - -```bash -export ANTHROPIC_API_KEY=sk-ant-... -omp -``` - -Then chat: - -``` -You: Create a simple Express server in src/server.ts -``` - -The agent reads, writes, and edits files, and executes commands via bash. - ---- - -## Usage - -### Slash Commands - -| Command | Description | -| ------------------------- | ----------------------------------------------------------------------------------------------- | -| `/settings` | Open settings menu (thinking, theme, queue mode, toggles) | -| `/model` | Switch models mid-session. Use `/model ` or `provider/model` to prefilter/disambiguate. | -| `/export [file]` | Export session to HTML file | -| `/dump` | Copy session transcript to clipboard | -| `/share` | Upload session as secret GitHub gist, get shareable URL (requires `gh` CLI) | -| `/session` | Show session info: path, message counts, token usage, cost | -| `/hotkeys` | Show all keyboard shortcuts | -| `/changelog` | Display full version history | -| `/tree` | Navigate session tree in-place (search, filter, label entries) | -| `/branch` | Create new conversation branch from a previous message | -| `/resume` | Switch to a different session (interactive selector) | -| `/login` | OAuth login for subscription-based models | -| `/logout` | Clear OAuth tokens | -| `/new` | Start a new session | -| `/copy` | Copy last agent message to clipboard | -| `/compact [instructions]` | Manually compact conversation context | - -### Editor Features - -**File reference (`@`):** Type `@` to fuzzy-search project files. Respects `.gitignore`. - -**Path completion (Tab):** Complete relative paths, `../`, `~/`, etc. - -**Drag & drop:** Drag files from your file manager into the terminal. - -**Multi-line paste:** Pasted content is collapsed to `[paste #N lines]` but sent in full. - -**Message queuing:** Submit messages while the agent is working. They queue and process based on queue mode (configurable via `/settings`). Press Escape to abort and restore queued messages to editor. - -### Keyboard Shortcuts - -**Navigation:** - -| Key | Action | -| ------------------------ | -------------------------------------------- | -| Arrow keys | Move cursor / browse history (Up when empty) | -| Option+Left/Right | Move by word | -| Ctrl+A / Home / Cmd+Left | Start of line | -| Ctrl+E / End / Cmd+Right | End of line | - -**Editing:** - -| Key | Action | -| ------------------------- | ----------------------------------------- | -| Enter | Send message | -| Shift+Enter | New line (Ctrl+Enter on Windows Terminal) | -| Ctrl+W / Option+Backspace | Delete word backwards | -| Ctrl+U | Delete to start of line | -| Ctrl+K | Delete to end of line | - -**Other:** - -| Key | Action | -| --------------------- | -------------------------------------------------------- | -| Tab | Path completion / accept autocomplete | -| Escape | Cancel autocomplete / abort streaming | -| Ctrl+C | Clear editor (first) / exit (second) | -| Ctrl+D | Exit (when editor is empty) | -| Ctrl+Z | Suspend to background (use `fg` in shell to resume) | -| Shift+Tab | Cycle thinking level | -| Ctrl+P / Shift+Ctrl+P | Cycle role models (slow/default/smol/plan) | -| Ctrl+L | Open model selector | -| Ctrl+O | Toggle tool output expansion | -| Ctrl+T | Toggle todo list expansion | -| Ctrl+G | Edit message in external editor (`$VISUAL` or `$EDITOR`) | - -### Bash Mode - -Prefix commands with `!` to execute them and add output to context: - -``` -!ls -la -!git status -!cat package.json | jq '.dependencies' -``` - -Output streams in real-time. Press Escape to cancel. Large outputs truncate at 2000 lines / 50KB. - -The output becomes part of your next prompt, formatted as: - -``` -Ran `ls -la` -``` - - -``` -``` - -Run multiple commands before prompting; all outputs are included together. - -### Image Support - -**Attaching images:** Include image paths in your message: - -``` -You: What's in this screenshot? /path/to/image.png -``` - -Supported formats: `.jpg`, `.jpeg`, `.png`, `.gif`, `.webp` - -**Inline rendering:** On terminals that support the Kitty graphics protocol (Kitty, Ghostty, WezTerm) or iTerm2 inline images, images in tool output are rendered inline. On unsupported terminals, a text placeholder is shown instead. - -Toggle inline images via `/settings` or set `terminal.showImages: false` in settings. - ---- - -## Sessions - -Sessions are stored as JSONL files with a **tree structure**. Each entry has an `id` and `parentId`, enabling in-place branching: navigate to any previous point with `/tree`, continue from there, and switch between branches while preserving all history in a single file. - -See [docs/session.md](docs/session.md) for the file format and programmatic API. - -### Session Management - -Sessions auto-save to `~/.omp/agent/sessions/` organized by working directory. - -```bash -omp --continue # Continue most recent session -omp -c # Short form - -omp --resume # Browse and select from past sessions -omp -r # Short form - -omp --no-session # Ephemeral mode (don't save) - -omp --session /path/to/file.jsonl # Use specific session file -omp --session a8ec1c2a # Resume by session ID (partial UUID) -``` - -**Resuming by session ID:** The `--session` flag accepts a session UUID (or prefix). Session IDs are visible in filenames under `~/.omp/agent/sessions//` (e.g., `2025-12-13T17-47-46-817Z_a8ec1c2a-5a5f-4699-88cb-03e7d3cb9292.jsonl`). The UUID is the part after the underscore. You can also search by session ID in the `omp -r` picker. - -### Context Compaction - -Long sessions can exhaust context windows. Compaction summarizes older messages while keeping recent ones. - -**Manual:** `/compact` or `/compact Focus on the API changes` - -**Automatic:** Enable via `/settings`. When enabled, triggers in two cases: - -- **Overflow recovery**: LLM returns context overflow error. Compacts and auto-retries. -- **Threshold maintenance**: Context exceeds `contextWindow - reserveTokens` after a successful turn. Compacts without retry. - -When disabled, neither case triggers automatic compaction (use `/compact` manually if needed). - -**Configuration** (`~/.omp/agent/settings.json`): - -```json -{ - "compaction": { - "enabled": true, - "reserveTokens": 16384, - "keepRecentTokens": 20000 - }, - "env": { - "ANTHROPIC_API_KEY": "sk-ant-...", - "OPENAI_API_KEY": "sk-proj-...", - "GEMINI_API_KEY": "AIzaSyD...", - "CUSTOM_VAR": "custom-value" - } -} -``` - -**Environment Variables (`env`):** - -- Automatically sets environment variables when the application starts -- Only sets variables that aren't already present in `Bun.env` -- Supports any environment variable, not just API keys -- Order of precedence: existing env vars > settings.json env vars > agent.db - -> **Note:** Compaction is lossy. The agent loses full conversation access afterward. Size tasks to avoid context limits when possible. For critical context, ask the agent to write a summary to a file, iterate on it until it covers everything, then start a new session with that file. The full session history is preserved in the JSONL file; use `/tree` to revisit any previous point. - -See [docs/compaction.md](docs/compaction.md) for how compaction works internally and how to customize it via hooks. - -### Branching - -**In-place navigation (`/tree`):** Navigate the session tree without creating new files. Select any previous point, continue from there, and switch between branches while preserving all history. - -- Search by typing, page with ←/→ -- Filter modes (Ctrl+O): default → no-tools → user-only → labeled-only → all -- Press `l` to label entries as bookmarks -- When switching branches, you're prompted whether to generate a summary of the abandoned branch (messages up to the common ancestor) - -**Create new session (`/branch`):** Branch to a new session file: - -1. Opens selector showing all your user messages -2. Select a message to branch from -3. Creates new session with history up to that point -4. Selected message placed in editor for modification - ---- - -## Configuration - -### Project Context Files - -Omp loads `AGENTS.md` (or `CLAUDE.md`) files at startup in this order: - -1. **Global:** `~/.omp/agent/AGENTS.md` -2. **Parent directories:** Walking up from current directory -3. **Current directory:** `./AGENTS.md` - -Use these for: - -- Project instructions and guidelines -- Common commands and workflows -- Architecture documentation -- Coding conventions -- Testing instructions - -```markdown -# Common Commands - -- npm run build: Build the project -- npm test: Run tests - -# Code Style - -- Use TypeScript strict mode -- Prefer async/await over promises -``` - -### Custom System Prompt - -Replace the default system prompt entirely by creating a `SYSTEM.md` file: - -1. **Project-local:** `.omp/SYSTEM.md` (takes precedence) -2. **Global:** `~/.omp/agent/SYSTEM.md` (fallback) - -This is useful when using omp as different types of agents across repos (coding assistant, personal assistant, domain-specific agent, etc.). - -```markdown -You are a technical writing assistant. Help users write clear documentation. - -Focus on: - -- Concise explanations -- Code examples -- Proper formatting -``` - -The `--system-prompt` CLI flag overrides both files. Use `--append-system-prompt` to add to (rather than replace) the prompt. - -### Custom Models and Providers - -Add custom models (Ollama, vLLM, LM Studio, etc.) via `~/.omp/agent/models.yml` (`models.json` is still supported for legacy configs): - -> See [models.yml provider integration guide](docs/models.md) for full schema, merge behavior, and provider integration patterns. - -```json -{ - "providers": { - "ollama": { - "baseUrl": "http://localhost:11434/v1", - "apiKey": "OLLAMA_API_KEY", - "api": "openai-completions", - "models": [ - { - "id": "llama-3.1-8b", - "name": "Llama 3.1 8B (Local)", - "reasoning": false, - "input": ["text"], - "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 }, - "contextWindow": 128000, - "maxTokens": 32000 - } - ] - } - } -} -``` - -**Supported APIs:** `openai-completions`, `openai-responses`, `openai-codex-responses`, `anthropic-messages`, `google-generative-ai`, `google-vertex` - -**API key resolution:** The `apiKey` field is checked as environment variable name first, then used as literal value. - -**API override:** Set `api` at provider level (default for all models) or model level (override per model). - -**Custom headers:** - -```json -{ - "providers": { - "custom-proxy": { - "baseUrl": "https://proxy.example.com/v1", - "apiKey": "YOUR_API_KEY", - "api": "anthropic-messages", - "headers": { - "User-Agent": "Mozilla/5.0 ...", - "X-Custom-Auth": "token" - }, - "models": [...] - } - } -} -``` - -**Authorization header:** Set `authHeader: true` to add `Authorization: Bearer ` automatically. - -**OpenAI compatibility (`compat` field):** - -| Field | Description | -| ------------------------- | ------------------------------------------- | -| `supportsStore` | Whether provider supports `store` field | -| `supportsDeveloperRole` | Use `developer` vs `system` role | -| `supportsReasoningEffort` | Support for `reasoning_effort` parameter | -| `maxTokensField` | Use `max_completion_tokens` or `max_tokens` | - -**Live reload:** The file reloads each time you open `/model`. Edit during session; no restart needed. - -**Model selection priority:** - -1. CLI args (`--provider`, `--model`) -2. First from `--models` scope (new sessions only) -3. Restored from session (`--continue`, `--resume`) -4. Saved default from settings -5. First available model with valid API key - -> omp can help you create custom provider and model configurations. - -### Settings File - -Settings are loaded from two locations and merged: - -1. **Global:** `~/.omp/agent/settings.json` - user preferences -2. **Project:** `/.omp/settings.json` - project-specific overrides (version control friendly) - -Project settings override global settings. For nested objects, individual keys merge. Settings changed via TUI (model, thinking level, etc.) are saved to global preferences only. - -Global `~/.omp/agent/settings.json` stores persistent preferences: - -```json -{ - "theme": "dark", - "modelRoles": { - "default": "anthropic/claude-sonnet-4-20250514" - }, - "defaultThinkingLevel": "medium", - "enabledModels": ["anthropic/*", "*gpt*", "gemini-2.5-pro:high"], - "queueMode": "one-at-a-time", - "shellPath": "C:\\path\\to\\bash.exe", - "hideThinkingBlock": false, - "collapseChangelog": false, - "compaction": { - "enabled": true, - "reserveTokens": 16384, - "keepRecentTokens": 20000 - }, - "skills": { - "enabled": true - }, - "retry": { - "enabled": true, - "maxRetries": 3, - "baseDelayMs": 2000 - }, - "terminal": { - "showImages": true - } -} -``` - -| Setting | Description | Default | -| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | --------------- | -| `theme` | Color theme name | auto-detected | -| `modelRoles` | Model assignments by role (e.g., `{"default": "...", "slow": "...", "smol": "...", "plan": "..."}`) | - | -| `defaultThinkingLevel` | Thinking level: `off`, `minimal`, `low`, `medium`, `high`, `xhigh` | - | -| `enabledModels` | Model patterns for cycling. Supports glob patterns (`github-copilot/*`, `*sonnet*`) and fuzzy matching. Same as `--models` CLI flag | - | -| `queueMode` | Message queue mode: `all` or `one-at-a-time` | `one-at-a-time` | -| `shellPath` | Custom bash path (Windows) | auto-detected | -| `hideThinkingBlock` | Hide thinking blocks in output | `false` | -| `collapseChangelog` | Show condensed changelog after update | `false` | -| `compaction.enabled` | Enable auto-compaction | `true` | -| `compaction.reserveTokens` | Tokens to reserve before compaction triggers | `16384` | -| `compaction.keepRecentTokens` | Recent tokens to keep after compaction | `20000` | -| `skills.enabled` | Enable skills discovery | `true` | -| `retry.enabled` | Auto-retry on transient errors | `true` | -| `retry.maxRetries` | Maximum retry attempts | `3` | -| `retry.baseDelayMs` | Base delay for exponential backoff | `2000` | -| `terminal.showImages` | Render images inline (supported terminals) | `true` | - ---- - -## Extensions - -### Themes - -Built-in themes: `dark` (default), `light`. Auto-detected on first run. - -Select theme via `/settings` or set in `~/.omp/agent/settings.json`. - -**Custom themes:** Create `~/.omp/agent/themes/*.json`. Custom themes support live reload. - -```bash -mkdir -p ~/.omp/agent/themes -cp $(npm root -g)/@oh-my-pi/pi-coding-agent/dist/theme/dark.json ~/.omp/agent/themes/my-theme.json -``` - -Select with `/settings`, then edit the file. Changes apply on save. - -> See [Theme Documentation](docs/theme.md) on how to create custom themes in detail. Omp can help you create a new one. - -**VS Code terminal fix:** Set `terminal.integrated.minimumContrastRatio` to `1` for accurate colors. - -### Custom Slash Commands - -Define reusable prompts as Markdown files: - -**Locations:** - -- Global: `~/.omp/agent/commands/*.md` -- Project: `.omp/commands/*.md` - -**Format:** - -```markdown ---- -description: Review staged git changes ---- - -Review the staged changes (`git diff --cached`). Focus on: - -- Bugs and logic errors -- Security issues -- Error handling gaps -``` - -Filename (without `.md`) becomes the command name. Description shown in autocomplete. - -**Arguments:** - -```markdown ---- -description: Create a component ---- - -Create a React component named $1 with features: $@ -``` - -Usage: `/component Button "onClick handler" "disabled support"` - -- `$1` = `Button` -- `$@` = all arguments joined - -**Namespacing:** Subdirectories create prefixes. `.omp/commands/frontend/component.md` → `/component (project:frontend)` - -### Skills - -Skills are self-contained capability packages that the agent loads on-demand. Omp implements the [Agent Skills standard](https://agentskills.io/specification), warning about violations but remaining lenient. - -A skill provides specialized workflows, setup instructions, helper scripts, and reference documentation for specific tasks. Skills are loaded when the agent decides a task matches the description, or when you explicitly ask to use one. - -**Example use cases:** - -- Web search and content extraction (Brave Search API) -- Browser automation via Chrome DevTools Protocol -- Google Calendar, Gmail, Drive integration -- PDF/DOCX processing and creation -- Speech-to-text transcription -- YouTube transcript extraction - -**Skill locations:** - -- Omp user: `~/.omp/agent/skills/*/SKILL.md` -- Omp project: `.omp/skills/*/SKILL.md` -- Claude Code: `~/.claude/skills/*/SKILL.md` and `.claude/skills/*/SKILL.md` -- Codex CLI: `~/.codex/skills/*/SKILL.md` - -**Format:** - -```markdown ---- -name: brave-search -description: Web search via Brave Search API. Use for documentation, facts, or web content. ---- - -# Brave Search - -## Setup - -\`\`\`bash -cd /path/to/brave-search && npm install -\`\`\` - -## Usage - -\`\`\`bash -./search.js "query" # Basic search -./search.js "query" --content # Include page content -\`\`\` -``` - -- `name`: Required. Must match parent directory name. Lowercase, hyphens, max 64 chars. -- `description`: Required. Max 1024 chars. Determines when the skill is loaded. - -**Disable skills:** `omp --no-skills` or set `skills.enabled: false` in settings. - -> See [docs/skills.md](docs/skills.md) for details, examples, and links to skill repositories. omp can help you create new skills. - -### Hooks - -Hooks are TypeScript modules that extend omp's behavior by subscribing to lifecycle events. Use them to: - -- **Block dangerous commands** (permission gates for `rm -rf`, `sudo`, etc.) -- **Checkpoint code state** (git stash at each turn, restore on `/branch`) -- **Protect paths** (block writes to `.env`, `node_modules/`, etc.) -- **Modify tool output** (filter or transform results before the LLM sees them) -- **Inject messages from external sources to wake up the agent** (file watchers, webhooks, CI systems) - -**Hook locations:** - -- Global: `~/.omp/agent/hooks/pre/*.ts`, `~/.omp/agent/hooks/post/*.ts` -- Project: `.omp/hooks/pre/*.ts`, `.omp/hooks/post/*.ts` -- CLI: `--hook ` (for debugging) - -**Quick example** (permission gate): - -```typescript -import type { HookAPI } from "@oh-my-pi/pi-coding-agent/hooks"; - -export default function (omp: HookAPI) { - omp.on("tool_call", async (event, ctx) => { - if (event.toolName === "bash" && /sudo/.test(event.input.command as string)) { - const ok = await ctx.ui.confirm("Allow sudo?", event.input.command as string); - if (!ok) return { block: true, reason: "Blocked by user" }; - } - return undefined; - }); -} -``` - -**Sending messages from hooks:** - -Use `omp.sendMessage(message, triggerTurn?)` to inject messages into the session. Messages are persisted as `CustomMessageEntry` and sent to the LLM. If the agent is streaming, the message is queued; otherwise a new agent loop starts if `triggerTurn` is true. - -```typescript -import * as fs from "node:fs"; -import type { HookAPI } from "@oh-my-pi/pi-coding-agent/hooks"; - -export default function (omp: HookAPI) { - omp.on("session_start", async () => { - fs.watch("/tmp/trigger.txt", () => { - const content = fs.readFileSync("/tmp/trigger.txt", "utf-8").trim(); - if (content) { - omp.sendMessage( - { - customType: "file-trigger", - content, - display: true, - }, - true, - ); // triggerTurn: start agent loop - } - }); - }); -} -``` - -> See [Hooks Documentation](docs/hooks.md) for full API reference. omp can help you create new hooks - -> See [examples/hooks/](examples/hooks/) for working examples including permission gates, git checkpointing, and path protection. - -### Custom Tools - -Custom tools let you extend the built-in toolset (read, write, edit, bash, ...) and are called by the LLM directly. They are TypeScript modules that define tools with optional custom TUI integration for getting user input and custom tool call and result rendering. - -**Tool locations (auto-discovered):** - -- Global: `~/.omp/agent/tools/*/index.ts` -- Project: `.omp/tools/*/index.ts` - -**Explicit paths:** - -- CLI: `--tool ` (any .ts file) -- Settings: `customTools` array in `settings.json` - -**Quick example:** - -```typescript -import { Type } from "@sinclair/typebox"; -import type { CustomToolFactory } from "@oh-my-pi/pi-coding-agent"; - -const factory: CustomToolFactory = (omp) => ({ - name: "greet", - label: "Greeting", - description: "Generate a greeting", - parameters: Type.Object({ - name: Type.String({ description: "Name to greet" }), - }), - - async execute(toolCallId, params, onUpdate, ctx, signal) { - const { name } = params as { name: string }; - return { - content: [{ type: "text", text: `Hello, ${name}!` }], - details: { greeted: name }, - }; - }, -}); - -export default factory; -``` - -**Features:** - -- Access to `omp.cwd`, `omp.exec()`, `omp.ui` (select/confirm/input dialogs) -- Session lifecycle via `onSession` callback (for state reconstruction) -- Custom rendering via `renderCall()` and `renderResult()` methods -- Streaming results via `onUpdate` callback -- Abort handling via `signal` parameter -- Multiple tools from one factory (return an array) - -> See [Custom Tools Documentation](docs/custom-tools.md) for the full API reference, TUI component guide, and examples. omp can help you create custom tools. - -> See [examples/custom-tools/](examples/custom-tools/) for working examples including a todo list with session state management and a question tool with UI interaction. - ---- - -## CLI Reference - -```bash -omp [options] [@files...] [messages...] -``` - -### Options - -| Option | Description | -| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `--provider ` | Provider: `anthropic`, `openai`, `google`, `mistral`, `xai`, `groq`, `cerebras`, `openrouter`, `zai`, `cursor`, `github-copilot`, `openai-codex`, `google-gemini-cli`, `google-antigravity`, or custom | -| `--model ` | Model ID | -| `--api-key ` | API key (overrides environment) | -| `--system-prompt ` | Custom system prompt (text or file path) | -| `--append-system-prompt ` | Append to system prompt | -| `--mode ` | Output mode: `text`, `json`, `rpc` (implies `--print`) | -| `--print`, `-p` | Non-interactive: process prompt and exit | -| `--no-session` | Don't save session | -| `--session ` | Use specific session file | -| `--session-dir ` | Directory for session storage and lookup | -| `--continue`, `-c` | Continue most recent session | -| `--resume`, `-r` | Select session to resume | -| `--models ` | Comma-separated patterns for model role cycling. Supports glob patterns (e.g., `anthropic/*`, `*sonnet*:high`) and fuzzy matching (e.g., `sonnet,haiku:low`) | -| `--no-tools` | Disable all built-in tools | -| `--tools ` | Restrict to comma-separated tool list (default: all tools enabled) | -| `--thinking ` | Thinking level: `off`, `minimal`, `low`, `medium`, `high`, `xhigh` | -| `--extension `, `-e` | Load an extension file (can be used multiple times) | -| `--no-extensions` | Disable extension discovery (explicit `-e` paths still work) | -| `--no-skills` | Disable skills discovery and loading | -| `--skills ` | Comma-separated glob patterns to filter skills (e.g., `git-*,docker`) | -| `--no-lsp` | Disable LSP integration | -| `--hook ` | Load a hook file (for debugging) | -| `--export [output]` | Export session to HTML | -| `--help`, `-h` | Show help | -| `--version`, `-v` | Show version | - -### File Arguments - -Include files with `@` prefix: - -```bash -omp @prompt.md "Answer this" -omp @screenshot.png "What's in this image?" -omp @requirements.md @design.png "Implement this" -``` - -Text files wrapped in `content`. Images attached as base64. - -### Examples - -```bash -# Interactive mode -omp - -# Interactive with initial prompt -omp "List all .ts files in src/" - -# Non-interactive -omp -p "List all .ts files in src/" - -# With files -omp -p @code.ts "Review this code" - -# JSON event stream -omp --mode json "List files" - -# RPC mode (headless) -omp --mode rpc --no-session - -# Continue session -omp -c "What did we discuss?" - -# Specific model -omp --provider openai --model gpt-4o "Help me refactor" - -# Model cycling with thinking levels -omp --models sonnet:high,haiku:low - -# Limit to specific provider with glob pattern -omp --models "github-copilot/*" - -# Read-only mode -omp --tools read,grep,find,ls -p "Review the architecture" - -# Export session -omp --export session.jsonl output.html -``` - -### Environment Variables - -| Variable | Description | -| ------------------------------------------- | ----------------------------------------------------------------- | -| `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, etc. | API keys for providers (see [API Keys & OAuth](#api-keys--oauth)) | -| `PI_CODING_AGENT_DIR` | Override the agent config directory (default: `~/.omp/agent`) | -| `VISUAL`, `EDITOR` | External editor for Ctrl+G (e.g., `vim`, `code --wait`) | - ---- - -## Tools - -All tools are enabled by default. Use `--tools ` to restrict to a subset. - -### Core Tools - -| Tool | Description | -| ------- | --------------------------------------------------------------------------------------------------------- | -| `read` | Read file contents. Images sent as attachments. Text: first 2000 lines. Use offset/limit for large files. | -| `write` | Write/overwrite file. Creates parent directories. | -| `edit` | Replace text in file with fuzzy whitespace matching. Fails if text appears multiple times or not found. | -| `bash` | Execute command. Returns stdout/stderr. Optional `timeout` parameter. | -| `grep` | Search file contents (regex or literal). Respects `.gitignore`. | -| `find` | Search for files by glob pattern. Respects `.gitignore`. | -| `ls` | List directory contents. Includes dotfiles. | - -### Additional Built-in Tools - -| Tool | Description | -| ------------ | ---------------------------------------------------------------------- | -| `task` | Spawn sub-agents for complex multi-step tasks | -| `lsp` | Language Server Protocol queries (go-to-definition, references, hover) | -| `todo_write` | Track task progress during sessions | -| `web_search` | Search the web | -| `fetch` | Fetch and process URLs | -| `python` | Execute Python code in IPython kernel | -| `notebook` | Edit Jupyter notebook cells | - -Example: `--tools read,grep,find,ls` for read-only code review. - -For adding new tools, see [Custom Tools](#custom-tools) in the Configuration section. - ---- - -## Programmatic Usage - -### SDK - -For embedding omp in Node.js/TypeScript applications, use the SDK: - -```typescript -import { createAgentSession, discoverAuthStorage, discoverModels, SessionManager } from "@oh-my-pi/pi-coding-agent"; - -const authStorage = await discoverAuthStorage(); -const modelRegistry = await discoverModels(authStorage); - -const { session } = await createAgentSession({ - sessionManager: SessionManager.inMemory(), - authStorage, - modelRegistry, -}); - -session.subscribe((event) => { - if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") { - process.stdout.write(event.assistantMessageEvent.delta); - } -}); - -await session.prompt("What files are in the current directory?"); -``` - -The SDK provides full control over: - -- Model selection and thinking level -- System prompt (replace or modify) -- Tools (built-in subsets, custom tools) -- Hooks (inline or discovered) -- Skills, context files, slash commands -- Session persistence (`SessionManager`) -- Settings (`SettingsManager`) -- API key resolution and OAuth - -**Philosophy:** "Omit to discover, provide to override." Omit an option and omp discovers from standard locations. Provide an option and your value is used. - -> See [SDK Documentation](docs/sdk.md) for the full API reference. See [examples/sdk/](examples/sdk/) for working examples from minimal to full control. - -### RPC Mode - -For embedding omp from other languages or with process isolation: - -```bash -omp --mode rpc --no-session -``` - -Send JSON commands on stdin: - -```json -{"type":"prompt","message":"List all .ts files"} -{"type":"abort"} -``` - -> See [RPC Documentation](docs/rpc.md) for the full protocol. - -### HTML Export - -```bash -omp --export session.jsonl # Auto-generated filename -omp --export session.jsonl output.html # Custom filename -``` - -Works with both session files and streaming event logs from `--mode json`. - ---- - -## Philosophy - -Omp is a fork of [Pi](https://github.com/badlogic/pi) by [Mario Zechner](https://github.com/badlogic). Pi is intentionally minimal—no MCP, no sub-agents, no built-in todos. Omp is the opposite: batteries included. - -**Yin to Pi's Yang.** Same foundation, different philosophy. Pi strips away; omp adds on. Both are valid approaches—pick what fits your workflow. - -**Full toolset by default.** Sub-agents, MCP, LSP, web search, Python execution, todo tracking—all enabled out of the box. Use `--tools` to restrict when needed. - -**Agent orchestration built-in.** The Task tool spawns specialized sub-agents (explore, plan, reviewer, task) for complex multi-step work. Parallelism and delegation, not just chat. - -**Multiple extension points.** [Skills](#skills) for on-demand capabilities, [Hooks](#hooks) for lifecycle control, [Custom Tools](#custom-tools) for new abilities, MCP for existing integrations. - ---- - -## Development - -### Debug Command - -`/debug` (hidden) writes rendered lines with ANSI codes to `~/.omp/agent/omp-debug.log` for TUI debugging, as well as the last set of messages that were sent to the LLM. - -For architecture and contribution guidelines, see [DEVELOPMENT.md](./DEVELOPMENT.md). - ---- - -## License - -MIT - -## See Also - -- [@oh-my-pi/pi-ai](https://www.npmjs.com/package/@oh-my-pi/pi-ai): Core LLM toolkit -- [@oh-my-pi/pi-agent-core](https://www.npmjs.com/package/@oh-my-pi/pi-agent-core): Agent framework +Package-specific references: +- [CHANGELOG](./CHANGELOG.md) +- [Documentation](./docs/) +- [DEVELOPMENT](./DEVELOPMENT.md)