peen
Overview
peen is the interactive terminal interface for Peen-SWE. It runs directly in your local environment or sandbox, providing a fast REPL loop with direct bash execution and optional Model Context Protocol (MCP) integration.
# Start an interactive session
peen
# Run directly on a specific task
peen -t "Fix TypeError in test_cli.py"
# Run in YOLO mode with an MCP server configuration
peen -t "Analyze logs and database" -y --mcp-config mcp.json
Command Line Options
| Flag | Type | Description |
|---|---|---|
-h, --help |
flag | Show help message and exit. |
-t, --task |
text | Task description to solve. If omitted, peen prompts interactively. |
-c, --config |
path | Path or filename of YAML config (defaults to peen.yaml or PEEN_CONFIG_PATH). |
-m, --model |
text | Model identifier (defaults to PEEN_MODEL_NAME or MSWEA_MODEL_NAME). |
-y, --yolo |
flag | Start in yolo mode (skip step-by-step confirmation). |
--mcp-config |
path | Path to JSON file defining Model Context Protocol servers to launch. |
Interactive Modes
During a session, you can switch execution modes at any prompt by typing the mode command, or by pressing Ctrl+C to interrupt running execution:
- Confirm mode (
/c): The agent outputs its proposed action and waits. PressEnterto approve, or type instructions to redirect it. Default mode. - YOLO mode (
/y): The agent executes every step automatically without prompting for confirmation. - Human mode (
/u): You take over the shell directly to run manual commands, inspect files, or edit state.
Model Context Protocol (MCP)
Peen-SWE supports Model Context Protocol servers via --mcp-config:
{
"mcpServers": {
"git": {
"command": "uvx",
"args": ["mcp-server-git", "--repository", "."]
},
"fetch": {
"command": "uvx",
"args": ["mcp-server-fetch"]
}
}
}
When an MCP config is supplied:
1. peen starts each configured server over stdio.
2. Tools are discovered dynamically via JSON-RPC.
3. The language model can invoke MCP tools as structured toolcalls alongside bash execution.
4. All MCP processes terminate cleanly when the session exits.
Session Artifacts & Trajectories
Every run records its full trajectory (prompts, toolcalls, outputs, token usage, and git diffs) to:
~/.peen/trajectories/<session_id>.json
The exact file path is printed to stdout at the start and conclusion of each run. You can inspect saved trajectories using the built-in inspector:
peen-inspector ~/.peen/trajectories/
Implementation Details
Default Configuration (peen.yaml)
agent:
system_template: |
You are Peen-SWE, a workshop-forged autonomous software engineering agent.
You interact directly with local terminals, codebases, and tool protocols to solve software engineering tasks with surgical precision.
instance_template: |
Task: {{task}}
You can execute bash commands and call Model Context Protocol (MCP) tools to inspect the environment, edit code, run tests, and verify solutions.
## Recommended Engineering Workflow
1. Explore & Reproduce: Inspect directory tree, search symbols, and reproduce the target issue or verify requirements.
2. Surgical Edit: Implement targeted, minimal code modifications.
3. Rigorous Test: Run local test suites or test reproduction scripts.
4. Verify & Submit: Once verified, complete the task by issuing:
`echo COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT`
followed by your summary. Do not combine this command with any other command.
## Execution Environment & Tools
- **Bash Execution**: Commands run in independent subshells. Prefix commands if directory changes are required (`cd path && ...`).
- **MCP Tools**: When configured, specialized MCP tools are available under `{server_name}__{tool_name}`.
- Each step should contain clear reasoning explaining your intent, followed by tool calls.
# Optional MCP Servers Configuration (Uncomment to enable)
# mcp:
# servers:
# # Example: Local SQLite MCP server
# sqlite:
# command: "uvx"
# args: ["mcp-server-sqlite", "--db-path", "./app.db"]
# # Example: Filesystem MCP server
# filesystem:
# command: "npx"
# args: ["-y", "@modelcontextprotocol/server-filesystem", "."]
CLI Entrypoint (peen.py)
#!/usr/bin/env python3
"""Peen-SWE: Compact, workshop-forged terminal agent built to shape and refine code with zero black-box bloat."""
import json
import os
from pathlib import Path
from typing import Any
import typer
import yaml
from rich.console import Console
from rich.panel import Panel
from peen import global_config_dir
from peen.agents import get_agent
from peen.agents.utils.prompt_user import _multiline_prompt
from peen.config import builtin_config_dir, get_config_from_spec
from peen.environments import get_environment
from peen.models import get_model
from peen.run.utilities.config import configure_if_first_time
from peen.utils.serialize import UNSET, recursive_merge
_DEFAULT_PEEN_YAML = (
Path("peen.yaml") if Path("peen.yaml").exists() else builtin_config_dir / "peen.yaml"
)
DEFAULT_CONFIG_FILE = Path(
os.getenv("PEEN_CONFIG_PATH", _DEFAULT_PEEN_YAML if _DEFAULT_PEEN_YAML.exists() else builtin_config_dir / "mini.yaml")
)
DEFAULT_OUTPUT_FILE = global_config_dir / "last_peen_run.traj.json"
BANNER = r"""[bold cyan]
___ ___ ___ _ _ ______ _____
| _ \/ __| __| \| |___/ __\ \ / / __|
| _/ (__| _|| .` |___\__ \\ \/\/ /| _|
|_| \___|___|_|\_| |___/ \_/\_/ |___|
[/bold cyan]
[dim]Compact, workshop-forged terminal agent · Bash + MCP superpowers[/dim]"""
_HELP_TEXT = """Peen-SWE: Autonomous code engineering agent in your local terminal.
Run tasks interactively or in autonomous YOLO mode with native Bash and MCP protocol tools.
"""
console = Console(highlight=False)
app = typer.Typer(rich_markup_mode="rich")
@app.command(help=_HELP_TEXT)
def main(
model_name: str | None = typer.Option(None, "-m", "--model", help="Model name (e.g. gpt-4o, claude-3-7-sonnet, ollama/deepseek-r1)"),
model_class: str | None = typer.Option(None, "--model-class", help="Model class to use (e.g. 'litellm')", rich_help_panel="Advanced"),
agent_class: str | None = typer.Option(None, "--agent-class", help="Agent class to use ('interactive' or 'default')", rich_help_panel="Advanced"),
environment_class: str | None = typer.Option(None, "--environment-class", help="Environment class ('local' or 'docker')", rich_help_panel="Advanced"),
task: str | None = typer.Option(None, "-t", "--task", help="Task or issue statement to execute"),
yolo: bool = typer.Option(False, "-y", "--yolo", help="Run without human confirmation prompts (autonomous execution)"),
cost_limit: float | None = typer.Option(None, "-l", "--cost-limit", help="Cost limit in USD. Set to 0 to disable."),
config_spec: list[str] = typer.Option([str(DEFAULT_CONFIG_FILE)], "-c", "--config", help="Configuration file path, name, or key=value overrides"),
mcp_config_path: Path | None = typer.Option(None, "--mcp-config", help="Path to dedicated MCP configuration file (.json or .yaml)"),
output: Path | None = typer.Option(DEFAULT_OUTPUT_FILE, "-o", "--output", help="Output trajectory file path"),
exit_immediately: bool = typer.Option(False, "--exit-immediately", help="Exit immediately upon task completion without prompt", rich_help_panel="Advanced"),
) -> Any:
console.print(Panel(BANNER, border_style="cyan"))
configure_if_first_time()
configs = [get_config_from_spec(spec) for spec in config_spec]
if isinstance(mcp_config_path, (str, Path)) and Path(mcp_config_path).exists():
path = Path(mcp_config_path)
raw_text = path.read_text(encoding="utf-8")
parsed_mcp = json.loads(raw_text) if path.suffix == ".json" else yaml.safe_load(raw_text)
configs.append({"mcp": parsed_mcp.get("mcp", parsed_mcp)})
configs.append({
"run": {"task": task or UNSET},
"agent": {
"agent_class": agent_class or UNSET,
"mode": "yolo" if yolo else UNSET,
"cost_limit": cost_limit if cost_limit is not None else UNSET,
"confirm_exit": False if exit_immediately else UNSET,
"output_path": output or UNSET,
},
"model": {
"model_class": model_class or UNSET,
"model_name": model_name or UNSET,
},
"environment": {
"environment_class": environment_class or UNSET,
},
})
config = recursive_merge(*configs)
if (run_task := config.get("run", {}).get("task", UNSET)) is UNSET:
console.print("\n[bold cyan]🔨 What code would you like to shape or refine today?[/bold cyan]")
run_task = _multiline_prompt()
console.print("[bold green]Task accepted. Starting agent...[/bold green]\n")
mcp_manager = None
if (mcp_config := config.get("mcp")) and mcp_config.get("servers"):
from peen.mcp import MCPManager
console.print(f"[bold cyan]Connecting MCP servers:[/bold cyan] {list(mcp_config['servers'].keys())}")
mcp_manager = MCPManager(mcp_config)
model = get_model(config=config.get("model", {}))
env = get_environment(config.get("environment", {}), default_type="local")
agent_config = {**config.get("agent", {})}
if mcp_manager is not None:
agent_config["mcp_manager"] = mcp_manager
agent = get_agent(model, env, agent_config, default_type="interactive")
agent.run(run_task)
if output_path := config.get("agent", {}).get("output_path"):
console.print(f"\n[dim]Trajectory saved to [bold green]'{output_path}'[/bold green][/dim]")
return agent
if __name__ == "__main__":
app()
Interactive Agent Class (interactive.py)
"""A small generalization of the default agent that puts the user in the loop.
There are three modes:
- human: commands issued by the user are executed immediately
- confirm: commands issued by the LM but not whitelisted are confirmed by the user
- yolo: commands issued by the LM are executed immediately without confirmation
"""
import json
import re
import sys
from typing import Literal, NoReturn
from rich.console import Console
from rich.rule import Rule
from peen.agents.default import AgentConfig, DefaultAgent
from peen.agents.utils.prompt_user import _multiline_prompt, prompt_session
from peen.exceptions import LimitsExceeded, Submitted, TimeExceeded, UserInterruption
from peen.models.utils.content_string import get_content_string
console = Console(highlight=False)
class InteractiveAgentConfig(AgentConfig):
mode: Literal["human", "confirm", "yolo"] = "confirm"
"""Whether to confirm actions."""
whitelist_actions: list[str] = []
"""Never confirm actions that match these regular expressions."""
confirm_exit: bool = True
"""If the agent wants to finish, do we ask for confirmation from user?"""
class InteractiveAgent(DefaultAgent):
_MODE_COMMANDS_MAPPING = {"/u": "human", "/c": "confirm", "/y": "yolo"}
def __init__(self, *args, config_class=InteractiveAgentConfig, **kwargs):
super().__init__(*args, config_class=config_class, **kwargs)
self.cost_last_confirmed = 0.0
def _interrupt(self, content: str, *, itype: str = "UserInterruption") -> NoReturn:
raise UserInterruption({"role": "user", "content": content, "extra": {"interrupt_type": itype}})
def add_messages(self, *messages: dict) -> list[dict]:
# Extend supermethod to print messages
for msg in messages:
role, content = msg.get("role") or msg.get("type", "unknown"), get_content_string(msg)
if role == "assistant":
console.print(
f"\n[red][bold]peen[/bold] (step [bold]{self.n_calls}[/bold], [bold]${self.cost:.2f}[/bold]):[/red]\n",
end="",
highlight=False,
)
else:
console.print(f"\n[bold green]{role.capitalize()}[/bold green]:\n", end="", highlight=False)
console.print(content, highlight=False, markup=False)
return super().add_messages(*messages)
def query(self) -> dict:
# Extend supermethod to handle human mode
if self.config.mode == "human":
match command := self._prompt_and_handle_slash_commands("[bold yellow]>[/bold yellow] "):
case "/y" | "/c":
pass
case _:
msg = {
"role": "user",
"content": f"User command: \n```bash\n{command}\n```",
"extra": {"actions": [{"command": command}]},
}
self.add_messages(msg)
return msg
try:
with console.status("Waiting for the LM to respond..."):
return super().query()
except TimeExceeded:
# A wall-clock limit can't be lifted by raising the step/cost limits
# (the next query re-checks the clock and raises again), so prompting
# would loop forever. Always stop cleanly instead.
raise
except LimitsExceeded:
if not self._stdin_is_interactive():
# No terminal to prompt for new limits -- e.g. an unattended
# `--yolo` run, or any run with stdin redirected from /dev/null
# (CI, a sandbox). Stop cleanly so the trajectory is saved with a
# LimitsExceeded exit status, instead of crashing on EOFError when
# reading input.
raise
console.print(
f"Limits exceeded. Limits: {self.config.step_limit} steps, ${self.config.cost_limit}.\n"
f"Current spend: {self.n_calls} steps, ${self.cost:.2f}."
)
self.config.step_limit = int(input("New step limit: "))
self.config.cost_limit = float(input("New cost limit: "))
return super().query()
@staticmethod
def _stdin_is_interactive() -> bool:
"""Whether an interactive terminal is available to prompt the user.
Returns False for unattended runs (e.g. `--yolo` in CI, or inside a
sandbox with stdin redirected from /dev/null), where calling ``input()``
would raise ``EOFError`` and crash the run.
"""
try:
return sys.stdin is not None and sys.stdin.isatty()
except (ValueError, OSError):
return False
def step(self) -> list[dict]:
# Override the step method to handle user interruption
try:
console.print(Rule())
return super().step()
except KeyboardInterrupt:
interruption_message = self._prompt_and_handle_slash_commands(
"\n\n[bold yellow]Interrupted.[/bold yellow] "
"[green]Type a comment/command[/green] (/h for available commands)"
"\n[bold yellow]>[/bold yellow] "
).strip()
if not interruption_message or interruption_message in self._MODE_COMMANDS_MAPPING:
interruption_message = "Temporary interruption caught."
self._interrupt(f"Interrupted by user: {interruption_message}")
def execute_actions(self, message: dict) -> list[dict]:
# Override to handle user confirmation and confirm_exit, with try/finally to preserve partial outputs
actions = message.get("extra", {}).get("actions", [])
commands = [
action["command"]
if action.get("tool_name", "bash") == "bash" and "command" in action
else f"[mcp:{action.get('tool_name')}] {json.dumps(action.get('arguments', {}))}"
for action in actions
]
outputs = []
try:
self._ask_confirmation_or_interrupt(commands)
for action in actions:
if action.get("tool_name", "bash") == "bash" or not self.mcp_manager:
outputs.append(self.env.execute(action))
else:
outputs.append(self.mcp_manager.execute(action))
except Submitted as e:
self._check_for_new_task_or_submit(e)
finally:
result = self.add_messages(
*self.model.format_observation_messages(message, outputs, self.get_template_vars())
)
return result
def _add_observation_messages(self, message: dict, outputs: list[dict]) -> list[dict]:
return self.add_messages(*self.model.format_observation_messages(message, outputs, self.get_template_vars()))
def _check_for_new_task_or_submit(self, e: Submitted) -> NoReturn:
"""Check if user wants to add a new task or submit."""
if self.config.confirm_exit:
message = (
"[bold yellow]Agent wants to finish.[/bold yellow] "
"[bold green]Type new task[/bold green] or [bold]Enter[/bold] to quit "
"([bold]/h[/bold] for commands)\n"
"[bold yellow]>[/bold yellow] "
)
user_input = self._prompt_and_handle_slash_commands(message).strip()
if user_input == "/u": # directly continue
self._interrupt("Switched to human mode.")
elif user_input in self._MODE_COMMANDS_MAPPING: # ask again
return self._check_for_new_task_or_submit(e)
elif user_input:
self._interrupt(f"The user added a new task: {user_input}", itype="UserNewTask")
raise e
def _should_ask_confirmation(self, action: str) -> bool:
return self.config.mode == "confirm" and not any(re.match(r, action) for r in self.config.whitelist_actions)
def _ask_confirmation_or_interrupt(self, commands: list[str]) -> None:
if not any(self._should_ask_confirmation(c) for c in commands):
return
prompt = (
f"[bold yellow]Execute {len(commands)} action(s)?[/] [green][bold]Enter[/] to confirm[/], "
"[red]type [bold]comment[/] to reject[/], or [blue][bold]/h[/] to show available commands[/]\n"
"[bold yellow]>[/bold yellow] "
)
match user_input := self._prompt_and_handle_slash_commands(prompt).strip():
case "" | "/y":
pass # confirmed, do nothing
case "/u": # Skip execution action and get back to query
self._interrupt("Commands not executed. Switching to human mode", itype="UserRejection")
case _:
self._interrupt(
f"Commands not executed. The user rejected your commands with the following message: {user_input}",
itype="UserRejection",
)
def _prompt_and_handle_slash_commands(self, prompt: str, *, _multiline: bool = False) -> str:
"""Prompts the user, takes care of /h (followed by requery) and sets the mode. Returns the user input."""
console.print(prompt, end="")
if _multiline:
return _multiline_prompt()
user_input = prompt_session.prompt("")
if user_input == "/m":
return self._prompt_and_handle_slash_commands(prompt, _multiline=True)
if user_input == "/h":
console.print(
f"Current mode: [bold green]{self.config.mode}[/bold green]\n"
f"[bold green]/y[/bold green] to switch to [bold yellow]yolo[/bold yellow] mode (execute LM commands without confirmation)\n"
f"[bold green]/c[/bold green] to switch to [bold yellow]confirmation[/bold yellow] mode (ask for confirmation before executing LM commands)\n"
f"[bold green]/u[/bold green] to switch to [bold yellow]human[/bold yellow] mode (execute commands issued by the user)\n"
f"[bold green]/m[/bold green] to enter multiline comment",
)
return self._prompt_and_handle_slash_commands(prompt)
if user_input in self._MODE_COMMANDS_MAPPING:
if self.config.mode == self._MODE_COMMANDS_MAPPING[user_input]:
return self._prompt_and_handle_slash_commands(
f"[bold red]Already in {self.config.mode} mode.[/bold red]\n{prompt}"
)
self.config.mode = self._MODE_COMMANDS_MAPPING[user_input]
console.print(f"Switched to [bold green]{self.config.mode}[/bold green] mode.")
return user_input
return user_input