Metadata-Version: 2.4
Name: onefirewall-ai
Version: 0.3.0
Summary: Coding agent CLI for the OneFirewall AI Gateway and any OpenAI-compatible provider
Author: OneFirewall
License-Expression: MIT
Keywords: ai,cli,onefirewall,llm,agent,gateway
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Utilities
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.28
Requires-Dist: rich>=13.0
Requires-Dist: prompt_toolkit>=3.0
Dynamic: license-file

# onefirewall-ai

> A coding agent for your terminal and VS Code, powered by the OneFirewall AI Gateway or any OpenAI-compatible provider.

[![PyPI](https://img.shields.io/pypi/v/onefirewall-ai)](https://pypi.org/project/onefirewall-ai/)
[![Python](https://img.shields.io/pypi/pyversions/onefirewall-ai)](https://pypi.org/project/onefirewall-ai/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

The agent reads and searches your code, edits files, runs commands and tests, and keeps going until the task is done, asking for your approval before anything changes.

## Install

```bash
pip install -U onefirewall-ai        # Python 3.10+
onefirewall-ai login                 # choose OneFirewall AI or any OpenAI-compatible provider
```

Then, inside a project:

```bash
onefirewall-ai                                   # interactive session
onefirewall-ai "fix the failing test in tests/test_api.py"   # one task
```

The VS Code extension (`vscode/onefirewall-ai-vscode`) uses this same engine.

## Using it

### Interactive session

```text
❯ why does login fail when the email has uppercase letters?
❯ @src/auth.py add rate limiting to the login handler
```

- Mention files with `@path` (Tab completes) to attach them.
- **Shift+Tab** cycles the permission mode: *ask before changes* → *auto-accept edits* → *auto* → *plan mode*.
- **Ctrl+C** interrupts the agent (it stops cleanly; the conversation stays usable). Ctrl+D exits.
- Alt+Enter or a trailing `\` inserts a newline.

| Command | What it does |
|---|---|
| `/model [name]` | Show or switch the model / OneFirewall workspace |
| `/mode default\|accept-edits\|auto\|plan\|bypass` | Change the permission mode |
| `/plan` | Toggle plan mode: the agent researches and proposes a plan before changing anything |
| `/undo` | Revert the file changes from the last turn |
| `/compact` | Summarize the conversation to free context |
| `/context`, `/cost` | Context window usage, token usage |
| `/todos` | Show the agent's task list |
| `/sessions`, `/resume [id]` | List and resume saved conversations |
| `/init` | Create or improve `AGENTS.md` for the project |
| `/mcp` | MCP server status |
| `/agents [show <id> \| stop <id\|all> \| new <name>]` | List agents and this session's runs, read a report, stop agents, create an agent file |
| `/new`, `/clear`, `/login`, `/help`, `/exit` | |

### One-shot and scripted use

```bash
onefirewall-ai "add type hints to utils.py"                    # live output, asks for approvals
cat error.log | onefirewall-ai "explain this error"             # piped input
onefirewall-ai -p "list the public API of src/" --output-format json      # non-interactive, for scripts/CI
onefirewall-ai -p "run the tests and fix failures" --permission-mode accept-edits
onefirewall-ai chat "what's the difference between TCP and UDP?"           # no tools
```

In `-p` (print) mode nobody can approve actions, so anything that needs approval is denied unless you pass `--permission-mode accept-edits` (edits allowed) or `bypass` (everything allowed — use only in a sandbox).

### Options

| Option | |
|---|---|
| `-c`, `--continue` | Continue the most recent session in this directory |
| `--resume <id>` | Resume a saved session |
| `--model <name>` | Use a specific model / workspace for this run |
| `--permission-mode <mode>` | `default`, `accept-edits`, `auto`, `plan`, `bypass` |
| `--cwd <dir>` | Work in another directory |
| `--max-steps <n>` | Limit model steps per turn (default 100) |
| `--output-format text\|json\|stream-json` | Output for `-p` |

Other commands: `onefirewall-ai sessions [view|delete] [id] [--all]`, `onefirewall-ai mcp list|add|remove`, `onefirewall-ai agents [new <name> [--user]]`, `onefirewall-ai login`, `onefirewall-ai version`.

## How the agent works

- **Grounded:** it searches (`grep`, `glob`) and reads files before answering or editing; edits are rejected unless the file was read first and hasn't changed since.
- **Precise edits:** exact-match replacement that preserves line endings (CRLF), BOM and encoding; tolerant of quote/whitespace/indentation slips; on a miss it shows the closest matching region so the model can correct itself.
- **Verifies:** runs your tests/linters/builds and reads the exit code and the end of the output.
- **Right shell:** on Windows it has a real `powershell` tool, plus `bash` when Git Bash is installed; on macOS/Linux `bash`.
- **Long tasks:** a todo list for multi-step work, agents that work in parallel in the background (see [Agents](#agents)), and automatic context compaction so long sessions don't overflow.
- **Recovers:** retries transient gateway errors with backoff, adapts to provider quirks, and guards against loops and stalls.

Tools: `read_file`, `edit_file`, `multi_edit`, `write_file`, `list_dir`, `glob`, `grep`, `bash` / `powershell`, `background_process`, `web_fetch`, `todo_write`, `task` and `agents` (agents), `ask_user`, `exit_plan_mode`, plus MCP tools.

## Agents

The agent can hand self-contained work to **agents**: separate workers with their own context and tools. Several run at the same time, in the background. The main agent tells you which agents are working and finishes its reply; you can keep chatting. When an agent finishes, its report comes back to the main agent as a new message: it checks what matters and tells you what was found, and gives the complete answer when the last one reports. (In `-p` runs, where nobody is there to see later replies, the turn waits for its agents instead.)

| Agent | |
|---|---|
| `explore` | Read-only research across the codebase; returns findings with `path:line` references |
| `plan` | Read-only; returns a concrete implementation plan (files, steps, risks, how to verify) |
| `general` | Multi-step tasks including edits, with the same tools as the main agent |

- Mention an agent to ask for it: `@explore how is caching invalidated?`
- Up to 4 agents run at once (`"max_agents"` in settings.json, or `ONEFIREWALL_MAX_AGENTS`).
- Ctrl+C / Stop ends the main agent's turn; background agents keep going and report when they finish. `/agents stop all` stops them.
- Research agents (`explore`, `plan`) are asked to wrap up after 20 tool calls and must report after 40.
- Approvals an agent needs are labelled with the agent (`Agent #a2 general asks:`).
- Each agent's transcript is saved next to the session (`~/.onefirewall-ai/projects/<project>/<session>.agents/`).

**Custom agents** are Markdown files in `<project>/.onefirewall/agents/` (shared with your team) or `~/.onefirewall-ai/agents/` (all your projects). Create one with `onefirewall-ai agents new security-reviewer` or `/agents new …`:

```markdown
---
name: security-reviewer
description: Reviews changes for security problems. Use after editing auth, input handling or crypto code.
tools: read_file, grep, glob, bash        # optional: limit its tools (MCP: mcp__server)
model: Fast                              # optional: another model / workspace
permission_mode: plan                    # optional: can only be stricter than the session's mode
max_steps: 40                            # optional
---
You are a security reviewer. Check the code you are pointed at for injection, auth bypass, secrets in code …
Report each finding with `path:line`, severity and a fix.
```

The main agent picks an agent by its `description`, so say when to use it. Project agents override user agents, which override the built-ins with the same name. `onefirewall-ai agents` lists them and shows files that failed to load.

## Permissions

| Mode | Behaviour |
|---|---|
| `default` | Asks before edits, shell commands (read-only ones like `git status` run freely), web fetches and MCP tools |
| `accept-edits` | File edits inside the project are applied without asking; commands still ask |
| `auto` | Edits and commands run without asking, except risky ones — pushing to git, recursive deletes, discarding changes, publishing, cloud/infra changes, `sudo`, `curl … \| sh`, global installs, writing outside the project — which pause with the reason |
| `plan` | Read-only. The agent investigates and presents a plan; approve it to start |
| `bypass` | Nothing asks. Only use in disposable environments |

When asked, answer **y** (yes), **a** (always allow this kind of action for the session), **n** (no), or type instructions to send back instead.

Persistent rules go in `~/.onefirewall-ai/settings.json` or `<project>/.onefirewall/settings.json`:

```json
{
  "permissions": {
    "default_mode": "default",
    "allow": ["bash(npm test*)", "powershell(git diff*)", "edit(src/**)", "web_fetch(docs.python.org)"],
    "deny": ["bash(git push*)", "read_file(.env)"]
  },
  "max_output_tokens": 8192,
  "context_window": 128000,
  "max_steps": 100,
  "max_agents": 4
}
```

## Project instructions

Put an `AGENTS.md` (or `ONEFIREWALL.md`) at the root of your repository with build/test commands, architecture notes and conventions; the agent follows it. Files in subdirectories apply when the agent works there. Personal, uncommitted overrides go in `ONEFIREWALL.local.md`; instructions for all your projects go in `~/.onefirewall-ai/AGENTS.md`. Run `/init` to generate a starting point.

## MCP servers

```bash
onefirewall-ai mcp add github --env GITHUB_TOKEN=${GITHUB_TOKEN} -- npx -y @modelcontextprotocol/server-github
onefirewall-ai mcp add docs --url https://example.com/mcp --header "Authorization: Bearer $TOKEN"
onefirewall-ai mcp list
```

User servers live in `~/.onefirewall-ai/mcp.json`. Servers defined by a repository (`.mcp.json`) run commands from that repository, so they only start after you trust the project when prompted.

## Providers and configuration

`onefirewall-ai login` writes `~/.onefirewall-ai/access.json`:

| Provider | Chat endpoint |
|---|---|
| `onefirewall` | `https://onefirewall.ai/api/v1/chat/completions` |
| `custom` | `{endpoint}/v1/chat/completions` (OpenAI, Groq, Together, Ollama, LM Studio, vLLM, …) |

Environment variables override the file (useful in CI): `ONEFIREWALL_PROVIDER`, `ONEFIREWALL_ENDPOINT`, `ONEFIREWALL_API_KEY`, `ONEFIREWALL_MODEL`, `ONEFIREWALL_CONTEXT_WINDOW`.

`~/.onefirewall-ai/SOUL.md` (persona) and `MEMORY.md` (facts about you; synced from the OneFirewall dashboard) are added to the agent's instructions once you edit them.

## Where data is stored

```text
~/.onefirewall-ai/
├── access.json            provider, model, API key (keep this file private)
├── settings.json          permissions and limits (optional)
├── mcp.json               MCP servers (optional)
├── projects/<dir>/*.jsonl saved sessions (full transcripts, used by --resume)
├── file-history/          backups used by /undo
└── tool-output/           full output of long commands
```

## Integrations

`onefirewall-ai --stdio` speaks a JSON-lines protocol (see [docs/PROTOCOL.md](docs/PROTOCOL.md)) used by the VS Code extension; any editor or tool can drive the agent with it.

## Development

```bash
pip install -e . pytest
pytest                      # unit + end-to-end tests against a fake model server
python evals/selftest.py    # validate the benchmark tasks
python evals/run.py         # run the benchmark against your configured model
```

## License

MIT © OneFirewall
