convez.ai
AgenteAutomaçãoIntermediário
tboulet

Alan Code Agent

tboulet/Alan-Code-agent

Agent de IA para coding com CLI, GUI e suporte a múltiplos modelos

Ver no GitHub
BomPluginScore · de 0 a 100

Agent de codificação Python open-source inspirado no Claude Code, utilizável via CLI, GUI ou como biblioteca Python. Suporta qualquer API compatível com LiteLLM e provedores locais (vLLM, SGLang, Ollama), com memória entre sessões, rastreamento de custos em tempo real e uma interface gráfica intuitiva.

Instalação

$npx convez-ai tboulet/Alan-Code-agent

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
26
Forks
3
Acompanhando
2
Saúde
42%
Último commit
há 1 semana
Versão
—
Issues abertas
0
Contribuidores
3

Casos de uso

  • Desenvolvimento assistido por IA com interface CLI ou web
  • Automação de tarefas de código e refatoração
  • Prototipagem rápida e iteração com histórico persistente

Veredito

Implementação robusta e versátil de um coding agent que diferencia-se pelo suporte multi-provider, memória persistente e interface gráfica bem pensada. Excelente para desenvolvedores que querem um assistant de código customizável e independente de um único provedor.

README

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

Alan Code

An open-source python coding agent, inspired by Claude Code. Usable in CLI, GUI, or as a Python library to build upon.

Alan Code implements many features of modern CLI agents, such as tool use, hooks, skills, context compaction and more, and adds unique ones such as cross-session memory, live cost tracking, and a GUI with a Chat, the model's exact perspective, and a git tree view.

Works with any LiteLLM compatible API key or provider, and several local model providers.

Highlights

  • Browser GUI with three panels — Chat, LLM Perspective (the model's exact view of the conversation), and a Git Tree of the agent's turns. --gui
  • Cross-session memory — per-project and global memory the agent reads/writes between sessions, with three modes (off / on / intensive).
  • Live cost + token tracking — estimated $ and token usage per API call, visible in-session.
  • Runs anywhere — Anthropic direct, any LiteLLM provider (OpenAI, OpenRouter, Gemini, …), or local models via vLLM / SGLang / Ollama, with a text-based tool-call fallback for models without native tool use.
  • Python library — drive the agent from your own code with sync, async, or streaming APIs. Build auto-fix loops, orchestrators, or custom UIs in a few lines.

Installation

Clone the repo and install in editable mode. Requires Python 3.11+.

git clone git@github.com:tboulet/Alan-Code-agent.git
cd Alan-Code-agent
pip install -e .

Quickstart

Set your provider's API key in the environment (ANTHROPIC_API_KEY, OPENAI_API_KEY, OPENROUTER_API_KEY, GEMINI_API_KEY, …).

alancode                                              # default: claude-sonnet-4-6
alancode --model openrouter/google/gemini-2.5-pro     # any provider/model
alancode --model ollama/llama3.1                      # local Ollama
alancode --model openai/my-model --base-url http://localhost:8000/v1   # vLLM / SGLang
alancode --gui                                        # browser GUI
alancode --resume                                     # last session

The provider goes inside the model string (ollama/..., openrouter/..., gemini/...). A bare Claude name (claude-sonnet-4-6) automatically uses the native Anthropic SDK; everything else routes through LiteLLM. See CLI flags for the full list.

Usage

CLI mode

A terminal-based chat interface. Type a prompt and press Enter; Alan will stream its reply, request permission before running tools, and persist the session so you can --resume later.

Commands

CommandPurpose
/helpList all available commands
/clearClear the conversation and start fresh
/compactManually trigger context compaction
/statusShow session info (model, tokens, cost)
/costToken usage and estimated $
/modelShow or switch the current model
/backendShow or switch the transport backend (auto / anthropic-native / scripted)
/saveAsk the agent to persist key info to memory
/commitStage + commit changes with an AI-generated message
/diffShow git diff of uncommitted changes
/memodiffShow differences in the agent's memory
/skillRun a skill — /skill list, /skill <name>, /skill create
/settingsShow or update session settings
/settings-projectShow project settings. Edit .alan/settings.json to change
/exitQuit the session

Other commands in docs/reference/slash-commands.md.

Parameters

alancode \
    --model [model_name] \              # bare (gpt-4o, claude-sonnet-4-6) or
                                        # provider/model (ollama/llama3.1, ...)
    --backend [auto/anthropic-native/scripted] \  # advanced; inferred from --model
    --api-key [key] \                   # or set environment variable
    --base-url [url] \                  # for local servers (http://localhost:8000/v1)
    --permission-mode [safe/edit/yolo] \
    [--gui] \                           # to launch in GUI mode
    [--resume]                          # to resume last session

Other parameters in docs/reference/cli.md.

Parameters can also be set in .alan/settings.json (auto-generated on first run) or modified at runtime with the /settings <key> <value> command.

GUI mode

Argument --gui launches a local GUI interface, with a Chat panel.

Additionally, it can also show:

  • an LLM Perspective panel that shows the model's conversation
  • a Git Tree panel that shows the git tree and the path of the agent conversation on it (feature in development).

The Git Tree feature (in development and unstable) allows you to move your agent over different branches of your git repo, and revert the conversation to previous points. To use with the /commit command.

As a python library

Alan Code can also be used as a Python library using the AlanCodeAgent class, allowing you to build agents or orchestrator systems on top of it.

Example 1 : Build a CLI agent in 10 lines of code:

from alancode import AlanCodeAgent

agent = AlanCodeAgent()

while True:
    try:
        message = input("> ")
    except (EOFError, KeyboardInterrupt):
        break
    if message.strip():
        print(agent.query(message))

Full example: examples/example_1_cli_agent.py. Run with python examples/example_1_cli_agent.py after installing the package.

Example 2 : Auto-fix loop — let the agent iterate until tests pass

Run your tests, feed the failures back to the agent, repeat until green. This is the kind of agentic orchestration you can't get from the plain CLI.

import subprocess
from alancode import AlanCodeAgent

agent = AlanCodeAgent(permission_mode="yolo")
agent.query("Read code_bugged.py and write a fixed version to code_fixed.py.")

for attempt in range(5):
    result = subprocess.run(
        ["pytest", "-q", "test_inventory.py"], capture_output=True, text=True,
    )
    if result.returncode == 0:
        print(f"All green after {attempt + 1} attempt(s).")
        break
    agent.query(f"Tests still fail:\n{result.stdout}\nFix the remaining bugs.")

Full example (with a buggy module and a test suite): examples/example_2_auto_fix_loop/run_alan.py.

Example 3 : Stream assistant text and tool calls live

For embedding in a web app, TUI, or WebSocket bridge — receive events as the agent produces them.

import asyncio
from alancode import AlanCodeAgent
from alancode.messages.types import AssistantMessage, TextBlock, ToolUseBlock

async def main():
    agent = AlanCodeAgent(permission_mode="yolo")
    async for event in agent.query_events_async("List files, then summarize."):
        if not isinstance(event, AssistantMessage):
            continue
        for block in event.content:
            if event.hide_in_api and isinstance(block, TextBlock):
                print(block.text, end="", flush=True)
            elif not event.hide_in_api and isinstance(block, ToolUseBlock):
                print(f"\n[tool: {block.name}({block.input})]")

asyncio.run(main())

Full example: examples/example_3_streaming_agent.py.

Programmatic mode — Alan as an embedded library

When Alan runs inside another program (a benchmark harness, a parent agent, an unattended pipeline) rather than as a developer assistant, pass programmatic=True:

agent = AlanCodeAgent(
    model="claude-sonnet-4-6",
    cwd="/path/to/experiment",
    permission_mode="yolo",
    programmatic=True,
    extra_tools=[MyDomainTool()],   # optional
)

This detaches Alan from project- and host-level state that would otherwise contaminate a controlled run: ~/.alan/ALAN.md, project ALAN.md, ~/.alan/memory/MEMORY.md, AGT bootstrap, and the network/git/ask-user tools (WebFetch, GitCommit, AskUserQuestion, Skill). Refine the tool set further with tools=[...] (full replacement) or disabled_tools=[...] (subtractive).

See docs/reference/python-api.md#programmatic-mode for details.

Features

Core

FeatureWhat it doesHow to use
Async agentic loopStreaming responses, thinking blocks, concurrent tool usedefault
Built-in toolsBash, File I/O, Grep/Glob, WebFetch, AskUserQuestion, SkillTool, GitCommitdefault
Context compactionSummarizes conversation when context fills upauto, or /compact
Universal backend (auto)LiteLLM transport — 100+ providers including OpenAI, OpenRouter, Gemini, Ollama, vLLM, …default for non-Claude models
Native Anthropic backendDirect Anthropic SDK with cache_control, native thinking, native tool_usedefault for bare claude-* names; force with --backend anthropic-native
Local modelsvLLM / SGLang / Ollama, with text-based tool-call fallback for models without native tool usedocs
HooksPre/post-tool shell hooks for guardrails or logging.alan/settings.json
SkillsUser-defined prompt + tool filter, discoverable at runtime/skill list, /skill create

Original to Alan Code

FeatureWhat it doesHow to use
Browser GUIChat + LLM Perspective + Git Tree panels on localhost--gui
LLM Perspective panelSee the model's exact view of the conversation — debug prompts, tool calls, compaction--gui, then toggle panel
Git Tree panelNavigate the agent's turn-by-turn git history; revert to any commit--gui, /move, /revert
Cross-session memoryPer-project + global memory the agent reads/writes between sessions. Modes: off (default), on (read at start, write on /save), intensive (read at start, write after every significant response)Set memory with /memory [on/intensive] or /save
Live cost trackingEstimated $ and token usage per API calldefault (docs)

Other

FeatureWhat it doesHow to use
Session persistenceSessions saved to disk; resume any time--resume, --continue <id>
Permission modesPer-tool gating with project-scoped rules — safe (ask each), edit (ask edits), yolo (no checks)--permission-mode <mode>
Git integrationAI-written commit messages, diffs/commit, /diff
Project + global instructionsAuto-loaded into the system promptALAN.md, ~/.alan/ALAN.md
Python library APISync query(), async query_async(), streaming query_events_async() — build loops, orchestrators, or custom UIs on topfrom alancode import AlanCodeAgent

Not (yet) implemented

Features of modern CLI coding agents that Alan Code does not ship with yet. Contributions welcome.

FeatureStatusNotes
Subagents / Task toolplannedSpawn isolated sub-conversations with their own context for parallel exploration or delegation.
MCP (Model Context Protocol)plannedConnect external tool servers (databases, APIs, IDEs) through the MCP standard.
Plan modeplannedForce the agent to write and get approval for a plan before touching code.
Image inputplannedPaste or attach images to the conversation; Gives Alan tools for image inference.
Stop / PreCompact / PostCompact hookspartialOnly Pre/PostToolUse hooks are implemented today.
WebSearch toolplannedThe WebFetch tool can fetch and summarize pages, but doesn't do active searching yet.

What's new

See CHANGELOG.md for the full history.

  • 2026-05-11 — Provider / model UX redesign — --provider is replaced by --backend (auto / anthropic-native / scripted); the upstream provider lives inside the model string as a prefix (ollama/llama3, openrouter/..., gemini/...). --backend is inferred from --model — bare Claude names use the native Anthropic SDK, everything else uses LiteLLM. Old --provider flag, settings key, and /provider command keep working as deprecated aliases for one release.
  • 2026-05-07 — Programmatic mode — AlanCodeAgent(programmatic=True, ...) runs Alan as a library component for benchmark harnesses, parent agents, and unattended pipelines. Skips host-level state (~/.alan/ALAN.md, ~/.alan/memory/, project ALAN.md, AGT bootstrap) and the network/git/ask-user tools. New tools= and disabled_tools= constructor params for fine-grained tool control.
  • 2026-04-28 — Prompt caching — Alan now places cache_control breakpoints on tool definitions, system prompt, and conversation history, for both providers. System prompt was optimized to avoid cache-killing dynamic content. Reduce the cost of Alan Code.

Further reading

Notes

  • This project is inspired by the Claude Code npm package, but is built from the ground up in python with our own architecture, and include additional features.
  • We are not responsible for any damage caused by the agent in yolo permission mode, although models are instructed to be cautious about destructive actions.
  • The name "Alan" comes from Alan Turing, a father of computer science along Claude Shannon.
Ver o original no GitHub

Bom para

Relacionados