convez.ai
AgenteDevOps & InfraestruturaAvançado
azri-cs

Reshell — Middleware de Execução Resiliente para Agents IA

azri-cs/reshell

Middleware que torna execução shell determinística e recuperável para agents IA

Ver no GitHub
InicialPluginScore · de 0 a 100

Camada determinística entre agentes IA (Claude Code, Cursor, etc.) e o shell do sistema operacional. Classifica falhas de comando em categorias estruturadas, propõe recuperações sem chamar LLM, compacta outputs grandes e aprende de erros anteriores via SQLite. Expõe 9 ferramentas e 2 prompts como servidor MCP.

Instalação

$npx convez-ai azri-cs/reshell

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
0
Forks
0
Acompanhando
0
Saúde
57%
Último commit
há 4 meses
Versão
—
Issues abertas
0
Contribuidores
2

Casos de uso

  • Permitir agents IA executarem comandos shell com recuperação automática de falhas
  • Reduzir context-window pollution ao compactar outputs grandes de comandos
  • Aprender padrões de falha anteriores para oferecer fixes instantâneos em recorrências
  • Validar e sanear comandos antes de execução, bloqueando operações perigosas

Veredito

Solução técnica sólida e bem-pensada para um problema real: agentes IA precisam executar shells com segurança e recuperabilidade. Abordagem determinística (sem LLM na recuperação) é elegante. Requer Rust e configuração por agente, mas o payoff é alto para workflows de automação sérios.

README

A tradução para o português deste README ainda está na fila.

Reshell (rsh) — Resilient Shell Execution Middleware for AI Agents

Reshell is a deterministic execution middleware that sits between an AI agent (Claude Code, OpenCode, Cursor, etc.) and the operating system shell. It transforms opaque command failures into structured, classified, and recoverable events — without ever calling an LLM to fix a shell error.


Features

  • Deterministic Failure Classification — Failures map to a taxonomy (R20–R27, R30) via regex-driven pattern matching and exit codes.
  • Zero-LLM Recovery Engine — Hardcoded, template-based recovery suggestions (install missing tools, fix permissions, POSIX-ify syntax, etc.).
  • Output Compaction — Prevents context-window pollution by truncating large outputs into head + structural skeleton + tail.
  • Pattern Memory — SQLite-backed learning from previous failures to provide high-confidence instant fixes on recurrence.
  • Safety Sandbox — Pre-exec validation blocks dangerous and interactive commands, optional command allowlist via ~/.reshell/allowlist.toml, and stderr secret scrubbing. There is no filesystem or network isolation.
  • MCP Server — Exposes 9 tools (rsh_exec, rsh_env, rsh_recover, rsh_compact, rsh_read_file, rsh_write_file, rsh_check, rsh_feedback, rsh_stats) and 2 prompts over framed MCP transport (Content-Length header + JSON body) on stdio.

Installation

Prerequisites

  • Rust toolchain (rustc + cargo) installed via rustup.
  • git installed to clone the repository.

You can install Rust/Cargo with:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source "$HOME/.cargo/env"

Prebuilt binaries

Download the latest release for your platform from the GitHub Releases page:

# Linux (x86_64)
curl -L -o rsh.tar.gz https://github.com/azri-cs/reshell/releases/latest/download/rsh-x86_64-unknown-linux-musl.tar.gz
tar xzf rsh.tar.gz
sudo mv rsh /usr/local/bin/

# macOS (Apple Silicon)
curl -L -o rsh.tar.gz https://github.com/azri-cs/reshell/releases/latest/download/rsh-aarch64-apple-darwin.tar.gz
tar xzf rsh.tar.gz
sudo mv rsh /usr/local/bin/

Homebrew

brew tap azri-cs/reshell
brew install reshell

From Source (requires Rust toolchain)

git clone https://github.com/azri-cs/reshell.git
cd reshell
cargo build --release
# Binary will be at target/release/rsh

Add to $PATH

cp target/release/rsh ~/.local/bin/
# or
sudo cp target/release/rsh /usr/local/bin/

Agent Configuration

Reshell exposes an MCP server on stdio (framed transport with Content-Length headers, per the MCP specification). Configure your agent to invoke rsh mcp.

Claude Code

Recommended project-local config (.mcp.json):

{
  "reshell": {
    "command": "rsh",
    "args": ["mcp"]
  }
}

If you are using a settings file with an mcpServers object, use the same server definition under mcpServers.reshell.

OpenCode

Add to your .opencode/mcp.json or workspace settings:

{
  "reshell": {
    "type": "local",
    "command": ["rsh", "mcp"],
    "enabled": true
  }
}

Cursor

Add to .cursor/mcp.json in your project root:

{
  "mcpServers": {
    "reshell": {
      "type": "stdio",
      "command": "rsh",
      "args": ["mcp"]
    }
  }
}

After adding the configuration, restart your agent. The agent will discover nine tools and two prompts.


Tools Reference

rsh_exec

Execute a shell command with resilient failure handling.

Input Schema:

{
  "command": "ls -la",
  "cwd": "/tmp",
  "timeout": 120,
  "env": {},
  "retry": true
}

Example Response (Success):

{
  "status": "success",
  "recovery_code": "R10",
  "recovery_class": "Success",
  "original_command": "ls -la",
  "suggestion": { "action": "none", "confidence": "high", "reason": "Command succeeded" },
  "output": { "stdout": "...", "stderr": "", "exit_code": 0, "truncated": false }
}

Example Response (Command Not Found — R22):

{
  "status": "failed",
  "recovery_code": "R22",
  "recovery_class": "Command Not Found",
  "original_command": "gh pr view",
  "suggestion": {
    "action": "install_missing_tool",
    "command": "brew install gh",
    "confidence": "high",
    "reason": "`gh` not found in $PATH."
  },
  "output": { "stdout": "", "stderr": "gh: command not found", "exit_code": 127, "truncated": false }
}

Additional fields (often present on failure or large output):

FieldMeaning
output_idID of stored stdout in the pattern DB (use with rsh_compact when truncated is true).
next_actionSuggested follow-up MCP tool name, parameters, and reason (e.g. call rsh_recover). On failure, params includes stderr (normalized, capped) so rsh_recover can reuse the same learned patterns as rsh_exec.
compaction_hintWhen stdout was truncated, how to call rsh_compact with output_id and a suggested view.
platformHost platform string for pattern matching context.
warningsNon-fatal notices (e.g. security-related).

rsh_env

Detect and describe the current shell environment (shell type, OS, available tools, package manager).

Input Schema: {}

rsh_recover

Apply a deterministic recovery strategy for a known failure class. When stderr is set (e.g. copy next_action.params.stderr from a failed rsh_exec), lookups use the same SQLite pattern memory as exec; otherwise only context is used (often the short classification reason).

Input Schema:

{
  "recovery_code": "R22",
  "original_command": "gh pr view",
  "context": "",
  "stderr": ""
}

stderr is optional. Prefer passing it when you have it so learned fixes (reuse_learned_fix) can match.

rsh_compact

Retrieve a compacted view of a large file or stdout previously stored from rsh_exec (via output_id).

Input Schema (file on disk):

{
  "file": "/var/log/syslog",
  "view": "skeleton"
}

Input Schema (stored command output):

{
  "output_id": "<uuid-from-rsh_exec>",
  "view": "errors_only"
}

Views: full, skeleton, diff, errors_only.

rsh_check

Session health check and short onboarding: verifies the server is up and summarizes the rsh_exec → rsh_recover → rsh_compact workflow. Input Schema: {}

rsh_read_file

Read a file through the safety sandbox (blocks path traversal and sensitive paths).

Input Schema:

{
  "path": "/path/to/file.txt"
}

rsh_write_file

Write content to a file through the safety sandbox (creates parent directories, blocks sensitive paths).

Input Schema:

{
  "path": "/path/to/file.txt",
  "content": "file contents here"
}

rsh_feedback

Record the outcome of a fix attempt to update pattern memory. Call this after trying a recovery suggestion.

Input Schema:

{
  "recovery_code": "R22",
  "original_command": "gh pr view",
  "suggested_command": "brew install gh && gh pr view",
  "success": true
}

rsh_stats

Get pattern memory statistics and runtime metrics: recovery attempts, pattern counts by recovery code, fix success rates, execution metrics.

Input Schema: {}


CLI Usage (Direct Mode)

Reshell can also be used directly from the terminal without an agent.

# Execute a command with structured JSON on stdout (default timeout 120s, retry on R25 enabled)
rsh exec --command "ls -la"
rsh exec --command "npm test" --cwd ./myapp --timeout 300
rsh exec --command "printenv FOO" -E FOO=bar

# Detect environment
rsh env

# Compact a large file, or a stored output from a prior exec
rsh compact --file /var/log/syslog
rsh compact --output-id "<uuid>" --view errors_only

Additional CLI flags

# Enable OverlayFS sandbox (Linux only)
rsh exec --command "npm install" --sandbox

# Generate shell completions
rsh completions bash
rsh completions zsh
rsh completions fish

# Extract JSON field
rsh compact --file package.json --jq ".dependencies"

# SSE transport for MCP
rsh mcp --transport sse --port 3000

Execution model

Commands are run as sh -c '<command>' by default. If retry is true (the default) and the first run is classified as R25 (environment mismatch), Reshell may re-run the same command using your login shell from $SHELL (e.g. bash or zsh) when it differs from sh. See src/env/detector.rs and src/exec/runner.rs for details.

Optional command allowlist

Advanced deployments can restrict which command names are permitted by creating ~/.reshell/allowlist.toml (blocklist remains the default if the file is missing or invalid). See comments in src/sandbox/allowlist.rs for the TOML shape.


Failure Taxonomy

CodeClassTriggerExample
R10SuccessExit 0—
R20Syntax ErrorExit 2, usage textinvalid option, unrecognized argument
R21Permission DeniedExit 126, 128Permission denied
R22Command Not FoundExit 127command not found
R23TimeoutSIGKILL / timeoutProcess exceeded time limit
R24Subcommand FailureExit 1 + patternnpm ERR!, pytest failed, make: ***
R25Environment MismatchShell mismatchBash-ism in Zsh
R26Output Overflowstdout > thresholdTruncated output
R27Blocked / Safety ViolationValidator / allowlistDangerous pattern, interactive editor, or allowlist deny
R30Fatal / UnknownNon-matchingRequires escalation

Architecture

AI Agent (Claude/OpenCode/Cursor)
    |
    | MCP stdio
    v
+---------------------------+
| Reshell MCP Server        |
|  - rsh_exec               |
|  - rsh_env                |
|  - rsh_recover            |
|  - rsh_compact            |
|  - rsh_check              |
+---------------------------+
    |
    v
+---------------------------+
| Command Validator         |
| Environment Detector      |
| Failure Classifier        |
| Recovery Engine           |
| Output Compactor          |
| Pattern Memory (SQLite)   |
| Safety Sandbox            |
+---------------------------+
    |
    v
   Shell (Bash / Zsh)

Testing

# Run unit tests embedded in modules
cargo test

# Run integration tests (spawns real MCP server process)
cargo test --test integration_tests

# Run benchmarks
cargo bench

Integration tests verify:

  • Happy path command execution via CLI and MCP.
  • Classification of R22 (Command Not Found).
  • Blocking of dangerous and interactive commands (R27).
  • Environment detection.
  • MCP initialize, tools/list, tools/call protocol compliance, including rsh_check.

Roadmap

  • Foundation — Command execution, timeout, structured JSON output
  • Failure Taxonomy — Regex-driven classifiers (R20–R30)
  • Recovery Engine — Deterministic suggestions per class
  • Output Compaction — Head/skeleton/tail truncation
  • Pattern Memory — SQLite-backed persistence
  • MCP Server — framed stdio transport (Content-Length headers) for Claude Code / OpenCode / Cursor
  • Optional command allowlist — ~/.reshell/allowlist.toml
  • OverlayFS sandbox — Filesystem isolation (Linux, opt-in)
  • Shell completions — bash, zsh, fish
  • SSE transport — HTTP SSE endpoint for MCP
  • jq-like extraction — JSON path queries in compact
  • Docker image — Multi-stage container build
  • Success metrics — Recovery rate, context savings, latency telemetry
  • Distribution — cargo install, Homebrew formula, crates.io publishing

License

MIT — See LICENSE for details.

Ver o original no GitHub

Bom para

Relacionados