sofos 0.1.22

An interactive AI coding agent for your terminal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
# Sofos Code

![](https://github.com/alexylon/sofos-code/actions/workflows/rust.yml/badge.svg)   [![Crates.io](https://img.shields.io/crates/v/sofos.svg?color=blue)](https://crates.io/crates/sofos)

A blazingly fast, interactive AI coding assistant powered by Claude or GPT, implemented in pure Rust, that can generate code, edit files, and search the web - all from your terminal.

Tested on macOS but should work on Linux and Windows as well.

<div align="center"><img src="/assets/screenshot.png" style="width: 800px;" alt="Sofos Code"></div>

## Table of Contents

- [Features]#features
- [Installation]#installation
- [Usage]#usage
  - [Quick Start]#quick-start
  - [Commands]#commands
  - [Image Vision]#image-vision
  - [Cost Tracking]#cost-tracking
  - [CLI Options]#cli-options
  - [Extended Thinking]#extended-thinking
- [Custom Instructions]#custom-instructions
- [Session History]#session-history
- [Available Tools]#available-tools
- [MCP Servers]#mcp-servers
- [Security]#security
- [Configuration]#configuration
- [Development]#development
- [Release]#release
- [Troubleshooting]#troubleshooting
- [Morph Integration]#morph-integration
- [License]#license
- [Acknowledgments]#acknowledgments
- [Links & Resources]#links--resources

## Features

- **Interactive REPL** - Multi-turn conversations with Claude or GPT
- **Markdown Formatting** - AI responses with syntax highlighting for code blocks
- **Image Vision** - Analyze local or web images, paste from clipboard with Ctrl+V
- **Session History** - Auto-save and resume conversations
- **Custom Instructions** - Project and personal context files
- **File Operations** - Read, write, edit, list, create (sandboxed)
- **Targeted Edits** - Diff-based `edit_file` for precise string replacements
- **Ultra-Fast Editing** - Optional Morph Apply integration (10,500+ tokens/sec)
- **File Search** - Find files by glob pattern (`**/*.rs`)
- **Code Search** - Fast regex search with ripgrep
- **Web Search** - Real-time info via Claude's/OpenAI's native search
- **Web Fetch** - Read documentation and web pages
- **Bash Execution** - Run tests and builds (read-only, sandboxed)
- **MCP Integration** - Connect to external tools via Model Context Protocol
- **Visual Diffs** - Syntax-highlighted diffs with line numbers
- **Iterative Tools** - Up to 200 tool calls per request
- **Context Compaction** - Summarizes older messages instead of dropping them
- **Cost Tracking** - Session token usage and cost estimates
- **Safe Mode** - Read-only operation mode

## Installation

**Requirements:** Anthropic API key ([get one](https://console.anthropic.com/)) or OpenAI API key ([get one](https://platform.openai.com/))

**Optional** (but highly recommended): `ripgrep` for code search ([install](https://github.com/BurntSushi/ripgrep#installation)), Morph API key for ultra-fast editing ([get one](https://morphllm.com/))

**Install:**

```bash
# Homebrew (could be behind `cargo install`)
brew tap alexylon/tap && brew install sofos

# Cargo (requires Rust 1.70+)
cargo install sofos

# From source
git clone https://github.com/alexylon/sofos-code.git
cd sofos-code && cargo install --path .
```

**Important:** Add `.sofos/` to `.gitignore` (contains session history and personal settings). Keep `AGENTS.md` (team-wide instructions).

## Usage

### Quick Start

```bash
# Set your API key (choose one)
export ANTHROPIC_API_KEY='your-anthropic-key'
# or
export OPENAI_API_KEY='your-openai-key'

# Optional: Enable ultra-fast editing
export MORPH_API_KEY='your-morph-key'

# Start Sofos
sofos
```

### Commands

- `/resume` - Resume previous session
- `/clear` - Clear conversation history
- `/think [on|off]` - Toggle extended thinking (shows status if no arg)
- `/compact` - Compress conversation history to free up context (also triggers automatically at 80% token usage)
- `/s` - Safe mode (read-only, prompt: **`λ:`**, blinking underscore (`_`) cursor)
- `/n` - Normal mode (all tools, prompt: **`λ>`**, default cursor)
- `/exit`, `/quit`, `/q`, `Ctrl+D` - Exit with cost summary
- `ESC` - Interrupt AI response

**Tab completion:** Press Tab for command suggestions, Shift+Tab to navigate backwards.

### Image Vision

Include image paths or URLs directly in your message, or paste images from clipboard:

```bash
# Paste from clipboard
Ctrl+V                        # Shows ① marker, paste multiple for ①②③
                               # Delete a marker to remove that image

# Local images
What's in this screenshot.png?
Describe ./images/diagram.jpg

# Paths with spaces - use quotes
What do you see in "/Users/alex/Documents/my image.png"?

# Web images
Analyze https://example.com/chart.png
```

**Formats:** JPEG, PNG, GIF, WebP (max 20MB local) | **Clipboard:** Ctrl+V pastes images on macOS, Linux, and Windows | **Spaces:** Wrap in quotes `"path/with space.png"` | **Permissions:** Outside workspace requires config

### Cost Tracking

Exit summary shows token usage and estimated cost (based on official API pricing).

### CLI Options

```
-p, --prompt <TEXT>          One-shot mode
-s, --safe-mode              Start in read-only mode (only read/list/web-search/image tools; no writes or bash commands)
-r, --resume                 Resume a previous session
    --api-key <KEY>          Anthropic API key (overrides env var)
    --openai-api-key <KEY>   OpenAI API key (overrides env var)
    --morph-api-key <KEY>    Morph API key (overrides env var)
    --model <MODEL>          Model to use (default: claude-sonnet-4-6)
    --morph-model <MODEL>    Morph model (default: morph-v3-fast)
    --max-tokens <N>         Max response tokens (default: 8192)
-t, --enable-thinking        Enable extended thinking (default: false)
    --thinking-budget <N>    Token budget for thinking (Claude only, default: 5120, must be < max-tokens)
-v, --verbose                Verbose logging
```

### Extended Thinking

Enable for complex reasoning tasks (disabled by default):

```bash
sofos -t                                             # Default 5120 token budget (Claude only)
sofos -t --thinking-budget 10000 --max-tokens 16000  # Custom budget (Claude only)
```

**Note:** Extended thinking works with both Claude and OpenAI models. 
For Claude, it enables the thinking protocol and `--thinking-budget` controls token allocation. 
For OpenAI (gpt-5 models), `/think on` sets high reasoning effort and `/think off` sets low reasoning effort. 
The `--thinking-budget` parameter only applies to Claude models.

## Custom Instructions/Context

**[`AGENTS.md`](https://agents.md)** (project root, version controlled) - Project context for AI agents, team-wide conventions, architecture
**`.sofos/instructions.md`** (gitignored) - Personal preferences

Both loaded at startup and appended to system prompt.

## Session History

Conversations auto-saved to `.sofos/sessions/`. Resume with `sofos -r` or `/resume`.

## Available Tools

**File Operations:**
- `read_file` - Read file contents
- `write_file` - Create or overwrite files
- `edit_file` - Targeted string replacement edits (no API key needed)
- `morph_edit_file` - Ultra-fast code editing (requires MORPH_API_KEY)
- `list_directory` - List a single directory's contents
- `glob_files` - Find files recursively by glob pattern (`**/*.rs`, `src/**/test_*.py`)
- `create_directory`, `delete_file`, `delete_directory`, `move_file`, `copy_file` - Standard file ops

**Code & Search:**
- `search_code` - Fast regex-based code search (requires `ripgrep`)
- `web_search` - Real-time web information via Claude's/OpenAI's native search
- `web_fetch` - Fetch URL content as readable text (documentation, APIs)
- `execute_bash` - Run tests and build commands (read-only, sandboxed)

**Image Vision:**
- `image` - View and analyze images (JPEG, PNG, GIF, WebP)

**MCP Tools:**
- Tools from configured MCP servers (prefixed with server name, e.g., `filesystem_read_file`)

**Note:** Only `read_file`, `list_directory`, and `image` can access paths outside workspace when explicitly allowed in config. All other operations are workspace-only.

Safe mode (`--safe-mode` or `/s`) restricts to: `list_directory`, `read_file`, `glob_files`, `web_search`, `web_fetch`, `image`.

## MCP Servers

Connect to external tools via MCP (Model Context Protocol). Configure in `~/.sofos/config.toml` or `.sofos/config.local.toml` (see the example in the "Configuration" section).

Tools auto-discovered, prefixed with server name (e.g., `filesystem_read_file`). See `examples/mcp_quickstart.md`.

**Popular servers:** https://github.com/modelcontextprotocol/servers

## Security

**Sandboxing (by default):**
- ✅ Full access to workspace files/directories
- ✅ Read-only access to outside workspace (requires explicit config)
- ❌ No writes, moves, or deletes outside workspace
- ❌ Bash always sandboxed to workspace

**Bash Permissions (3-Tier System):**

1. **Allowed (auto-execute):** Build tools (cargo, npm, go), read-only commands (ls, cat, grep), system info (pwd, date), git read-only
2. **Forbidden (always blocked):** rm, mv, cp, chmod, sudo, mkdir, cd, kill, shutdown
3. **Ask (prompt user):** Unknown commands require approval; can be remembered in config

## Configuration

Permissions are stored in `.sofos/config.local.toml` (workspace-specific, gitignored) or `~/.sofos/config.toml` (global, optional). Local config overrides global.

**Example:**

```toml
[permissions]
allow = [
  # Read permissions - for accessing files/directories outside workspace
  "Read(~/.zshrc)",           # Specific file
  "Read(~/.config/**)",       # Recursive
  "Read(/etc/hosts)",         # Absolute path
  
  # Bash permissions - for command execution
  "Bash(custom_command)",
  "Bash(pattern:*)",
]

deny = [
  # Read denials
  "Read(./.env)",
  "Read(./.env.*)",
  "Read(./secrets/**)",
  
  # Bash denials
  "Bash(dangerous_command)",
]

ask = [
  # Only for Bash commands (prompts for approval)
  "Bash(unknown_tool)",
]

[mcp-servers.company-internal]
command = "/usr/local/bin/company-mcp-server"
args = ["--config", "/etc/company/mcp-config.json"]
env = { "COMPANY_API_URL" = "https://internal.company.com" }

[mcp-servers.github]
command = "npx"
args = ["-y", "@modelcontextprotocol/server-github"]
env = { "GITHUB_TOKEN" = "ghp_YOUR_TOKEN" }

[mcp-servers.api]
url = "https://api.example.com/mcp"
headers = { "Authorization" = "Bearer token123" }
```

**Rules\*:**
- Workspace files: allowed by default unless in `deny` list
- Outside workspace: denied by default unless in `allow` list
- Glob patterns supported: `*` (single level), `**` (recursive)
- Tilde expansion: `~` → home directory
- `ask` only works for Bash commands, not Read permissions

\* These rules do not restrict MCP server command paths

## Development

```bash
cargo test                    # Run tests
cargo build --release         # Build release
RUST_LOG=debug sofos          # Debug logging
```

**Structure:**

```
src/
├── main.rs              # Entry point
├── cli.rs               # CLI argument parsing
├── clipboard.rs         # Clipboard image paste (Ctrl+V)
├── error.rs             # Error types
├── error_ext.rs         # Error extensions
├── config.rs            # Configuration
│
├── api/                 # API clients
│   ├── anthropic.rs     # Claude API client (+ streaming)
│   ├── openai.rs        # OpenAI API client
│   ├── morph.rs         # Morph Apply API client
│   ├── types.rs         # Message types and serialization
│   └── utils.rs         # Retries, error handling
│
├── mcp/                 # MCP (Model Context Protocol)
│   ├── config.rs        # Server configuration loading
│   ├── protocol.rs      # Protocol types (JSON-RPC)
│   ├── client.rs        # Client implementations (stdio, HTTP)
│   └── manager.rs       # Server connection management
│
├── repl/                # REPL components
│   ├── mod.rs           # Main REPL loop
│   ├── clipboard_edit_mode.rs # Ctrl+V interception via custom EditMode
│   ├── conversation.rs  # Message history and compaction
│   ├── prompt.rs        # Prompt rendering
│   ├── request_builder.rs   # API request construction
│   └── response_handler.rs  # Response and tool iteration
│
├── session/             # Session management
│   ├── history.rs       # Session persistence
│   ├── state.rs         # Runtime session state
│   └── selector.rs      # Session selection TUI
│
├── tools/               # Tool implementations
│   ├── filesystem.rs    # File operations
│   ├── bashexec.rs      # Bash execution
│   ├── codesearch.rs    # Code search (ripgrep)
│   ├── image.rs         # Image handling
│   ├── permissions.rs   # Permission system
│   ├── tool_name.rs     # Type-safe tool name enum
│   ├── types.rs         # Tool definitions
│   └── utils.rs         # Confirmations, HTML-to-text
│
├── ui/                  # UI components
│   ├── mod.rs           # UI utilities, markdown renderer
│   ├── syntax.rs        # Syntax highlighting
│   └── diff.rs          # Syntax-highlighted diffs with line numbers
│
└── commands/            # Built-in commands
    └── builtin.rs       # Command implementations
```

See `AGENTS.md` for detailed conventions.

## Release

This project uses **cargo-release** for automated versioning and publishing.

**Quick commands:**

```bash
# Preview the release
cargo release patch

# Execute the release
cargo release patch --execute

# Release specific version
cargo release [patch|minor|major] --execute
```

The release workflow automatically:
1. Bumps version in `Cargo.toml`
2. Runs tests and formatting checks
3. Updates `CHANGELOG.md`
4. Publishes to crates.io
5. Creates release commit and Git tag
6. Pushes to remote repository

**For detailed instructions**, see [RELEASE.md](RELEASE.md).

## Troubleshooting

- **API errors:** Check connection and API key
- **Path errors:** Use relative paths for workspace, or add `Read(path)` to config for outside access
- **Build errors:** `rustup update && cargo clean && cargo build`
- **Images with spaces:** Wrap path in quotes

## Morph Integration

Optional ultra-fast code editing via Morph Apply API (10,500+ tokens/sec, 96-98% accuracy). Enable with `MORPH_API_KEY`.

## License

MIT License

## Acknowledgments

Built with Rust and powered by Anthropic's Claude or OpenAI's GPT. Morph Apply integration for fast edits. Inspired by Aider and similar tools.

## Links & Resources

- [GitHub]https://github.com/alexylon/sofos-code
- [Crates.io]https://crates.io/crates/sofos

---

**Disclaimer:** Sofos Code may make mistakes. Always review generated code before use.

[![forthebadge](https://forthebadge.com/images/badges/made-with-rust.svg)](https://forthebadge.com)