AI-Commander: a ralph-loop AI agent giving LLMs shell access via function calling (TUI + CLI)
pip install aic-agent==2.6.1 Copy PIP instructions
PyPI package: aic-agent — install with pip install aic-agent (the command is aic).
AI-Commander is a ralph-loop AI agent that provides shell access and task planning capabilities to Large Language Models through function calling. It runs a tight agent loop: it plans, executes shell commands, observes the results, and iterates until the requested task is complete — all while you stay in control through an approval gate.
pip install aic-agent This installs the aic command plus every runtime dependency, including the Textual TUI, so the TUI and LLM-based context compression work out of the box. (py-landlock is installed only on Linux; elsewhere the agent simply runs unsandboxed.)
pip install --upgrade aic-agent From a checkout of this repository git clone https://github.com/ortegaalfredo/AICommander cd AICommander python3 -m venv venv source venv/bin/activate pip install . Or, to install in editable mode while hacking on the code:
pip install -e . Alternatively, install only the dependencies and run the script directly:
pip install -r requirements.txt python3 aic.py ... Note: The py-landlock package is only used on Linux and is optional — the agent runs unsandboxed if it is not installed.
AI-Commander is a single-file script. Run it from the repository root with python3 aic.py, or use the aic command installed by the aic-agent package:
# Installed via pip (package: aic-agent) aic \ --api-base https://api.example.com/v1 \ --model your-model-name \ --api-key YOUR_API_KEY \ "your task request" # From a repository checkout python3 aic.py \ --api-base https://api.example.com/v1 \ --model your-model-name \ --api-key YOUR_API_KEY \ "your task request" The TUI starts with no request and waits for you to type one in the prompt panel. In --nogui mode a request is required on the command line.
In --nogui mode the exit status tells scripts how the run ended: 0 task complete, 1 error, 2 step or iteration limit reached, 130 stopped.
# Run in the TUI (default) python3 aic.py --api-base https://api.example.com/v1 \ --model gpt-4o --api-key sk-... "List all files in this directory" # Run in plain CLI mode python3 aic.py --nogui --api-base https://api.example.com/v1 \ --model gpt-4o --api-key sk-... "Summarize the contents of aic.py" # Auto-approve all commands (useful for testing / scripting) python3 aic.py --auto-approve --api-base https://api.example.com/v1 \ --model gpt-4o --api-key sk-... "Set up a new Python project" # Use the truncation algorithm and a smaller, faster prompt python3 aic.py --fast --api-base https://api.example.com/v1 \ --model gpt-4o --api-key sk-... "List all files" # Headless: configuration from the environment, prompt on stdin, JSON events export AIC_API_BASE=https://api.example.com/v1 AIC_MODEL=gpt-4o AIC_API_KEY=sk-... cat task.md | aic --json --auto-approve --verify "pytest -q" > events.jsonl # Ralph loop: PROMPT.md re-run with a fresh context until the objective is done aic --nogui --auto-approve --loop PROMPT.md --max-iterations 20 --verify "make test" How it works The agent receives your task request. It plans the next step and may emit thinking tokens. It proposes shell commands, which you approve or auto-approve. Commands run (optionally sandboxed and time-limited), and their output is fed back to the model. The loop repeats until the task is considered complete. All I/O is routed through the EventSink abstraction, so the same agent logic runs unchanged in both the TUI and --nogui modes.
The model's thinking (reasoning_content) is sent back with its turns for the rest of the current task ("preserved thinking"), as interleaved-thinking models such as GLM and DeepSeek expect; without it they see their earlier turns with empty thinking and progressively stop thinking. It is cleared when you send a new request, and if an endpoint refuses it, AI-Commander retries without it and stops sending it for the session.
The agent has six tools. read_file, edit_file (exact string replacement) and write_file view and change files without shell quoting, so weaker models stop breaking files with sed and heredocs; each goes through the approval gate, which shows edits as a diff. todo keeps the agent's task list (shown back to it after the context is compacted, and saved in the session), and task_complete(summary) ends the task.
execute_bash(command) runs everything else with bash (/bin/sh if bash is missing; PowerShell on Windows) in a pseudo-terminal (PTY). The PTY gives the command a real terminal environment (so interactive tools and tput-style programs work) and lets the agent capture output, enforce a timeout, and kill the whole process group when needed. The working directory carries over between calls: a cd persists (shell variables and exports do not), relative paths in the file tools resolve against it, and it is saved in the session. --verify always runs where AI-Commander was started.
Output is streamed live to the console panel. Past --max-output-bytes the result keeps the first 30% and the last 70%, cut at whole lines, with a marker naming a temporary file that holds the full output, and the literal sentinel output too long: truncated appended. A command whose output passes 1 MiB (or 5x --max-output-bytes, whichever is larger) is killed.
With background: true, execute_bash starts the command in the background and returns at once with its pid and log file; when the job exits, its exit code and last lines are reported to the agent at its next step. Jobs still running when AI-Commander exits are killed, and the temporary files (saved outputs, job logs) are removed.
The default Textual interface is a Norton-Commander-style split screen:
The agent runs in a background thread and communicates with the UI through a queue; the UI never blocks on the agent. Typing while the agent works queues a steering message that is delivered at its next step.
Type any of the following in the prompt (Tab completes them). They are UI controls, so they are not added to prompt history:
While the Shell tab has the focus, every key except the function keys and the agent-tab keys (Ctrl+T, Ctrl+G) goes to the shell (so Ctrl+C, Ctrl+F, Escape, Tab and arrows work as in a terminal); use F6 or the mouse to leave it.
Prompt history is persisted to ~/.aic_history (up to 1000 entries, one per line with newlines escaped, so multi-line prompts survive) and loaded at startup. The file is opened before the Landlock sandbox is applied, so new prompts are saved even though the sandbox blocks other writes to $HOME. Up/Down navigation preserves your in-progress text, and Ctrl+R opens a reverse search that filters history newest-first; Ctrl+R cycles to the next older match, Enter accepts a match back into the prompt, and Escape/Ctrl+G cancels.
By default every command the agent proposes must be approved before it runs. This keeps you in control of what executes on your system. The TUI shows the command (syntax highlighted) in a dialog:
The file tools go through the same gate: edit_file and write_file show the change as a unified diff (in --nogui mode the diff is printed before the question). An edit whose old_string is missing or ambiguous is refused before you are asked.
Commands that only read run without asking: every command of the pipeline or list must be one of ls, cat, head, tail, wc, grep, rg, find, cd, pwd, echo, stat, du, diff, sort, uniq, cut, jq, git status/diff/log/show/blame/ls-files/grep, ... (extend the list with $AIC_READ_ONLY_COMMANDS), with no $(...), backticks, redirection other than to /dev/null, background &, or writing option (find -exec/-delete, sort -o, ...). Anything else asks. read_file runs without asking too. --confirm-reads turns this off, so every call asks.
For a moment after the dialog opens its keys are ignored, so typing that was meant for the prompt can never approve a command by accident. In --nogui mode the same choices are asked on the terminal; a blank answer, end of input or Ctrl+C never approves.
You can toggle auto-approve at any time with F2 or /autoapprove (/aa), or start with --auto-approve. When auto-approve is ON, all commands run without asking (the status line shows AUTO-APPROVE) — useful for testing and scripting, but be ready to stop the agent (F9) if a command misbehaves.
--loop PROMPT.md (or /loop in the TUI) runs the ralph loop pattern: the same prompt file is given to the agent again and again, and every iteration starts with a fresh context: the system prompt plus the file, re-read each time so you can edit it while the loop runs. Nothing is remembered between iterations except what is on disk, so the system prompt tells the agent to:
The loop stops on objective_complete (or a LOOPCOMPLETE line), when an iteration fails (API error), when you stop it, or after --max-iterations (default 10, 0 = unlimited). An iteration that hits --max-steps just ends, and the next one starts fresh. Combine it with --verify so "done" has to pass your tests.
Because every iteration starts empty, /loop in the TUI replaces the current conversation (and the session file mirrors only the running iteration). AI-Commander does not commit for you: if you want a commit per iteration, say so in PROMPT.md.
If the working directory has an AGENTS.md (or, failing that, a CLAUDE.md), its contents (up to 16000 characters) are added to the system prompt of every run, so project conventions and build/test commands reach the model without being repeated in each request.
The agent finishes by calling task_complete with a summary for you, on its own: a task_complete sent alongside other tool calls is refused, so the agent has seen their results before it finishes. For models that write it instead, a TASKCOMPLETE line still ends the run; it only counts on a line of its own or at the end of the reply, so "I'll say TASKCOMPLETE once the tests pass" does not. With --verify CMD, completion is checked by running CMD (with the normal timeout and output limits, no approval needed): exit 0 accepts it; anything else sends the output back to the model as [VERIFY FAILED] and the run continues.
The prompt budget is --max-prompt-len (default 80,000 tokens). For models that accept a max_tokens request parameter (all non-gpt models), the budget is reduced by the output reservation (max_tokens, 16,000) so the prompt leaves room for the completion inside the context window:
prompt_budget = max_prompt_len - max_tokens (for non-gpt models) prompt_budget = max_prompt_len (for gpt models) Token counts are estimated locally with a conservative heuristic (~3 characters per token plus per-message overhead). Exact numbers come from the API's usage stats once each call finishes and are shown in the status bar. If the server still rejects a prompt as too long (tokenizers differ, e.g. for CJK text), the history is compressed harder and the request retried.
--compress-alg truncate (or --fast) is the simpler, cheaper algorithm. It always preserves the system prompt, the first user instruction and the request that started the current run, so the agent never forgets either its primary objective or what it is working on now. It works in two passes:
Both passes stop once the retained history fits within --compress-target (default 40%) of the budget, leaving headroom so several new turns fit before the next compression. Truncating down to the full budget would make every following prompt exceed the limit again and re-compress on each step, slowly losing more history than necessary.
--compress-alg context-compressor-llm (the default) is a Factory.ai-style anchored-summary incremental compressor, the algorithm of the context-compressor-llm package, built into AI-Commander (no extra dependency). When the non-system log exceeds the budget it:
The system prompt is kept byte-identical at the front of the retained context so unchanged prefixes are never re-prefilled (important on systems with slow prompt processing / prefix caching); the summary is appended to it after a [Prior conversation summary] marker. Each new compression folds the previous summary into the new one, so summaries never pile up, and only the summary itself is kept (not the model's scratchpad). The first user instruction and the current request are preserved verbatim, and a fallback user message is appended if aggressive compression would leave no user query at all (some endpoints reject that). When nothing can be summarized, the truncate algorithm is applied instead, as it is when the summarizer call fails.
Use --compress-target to control how much headroom is retained (default 0.4 = 40%). A higher value keeps more history but triggers compression sooner; a lower value compresses harder but loses more context.
AI-Commander mirrors the complete conversation history to a JSON file and reloads it on every startup, so nothing already produced is lost to a crash, a kill, a closed terminal, or Ctrl+C.
The status line at startup reports what happened, e.g. [SESSION] Persisting session to /project/.aicsession or [SESSION] Restored 14 message(s) from .aicsession (session 20260828_134851, step 4).
Plain, indented, UTF-8 JSON — deliberately simple enough to read and edit:
{ "aic_session_version": 1, "session_id": "20260828_134851", "updated_at": "2026-08-28T13:52:58", "reason": "tool_result", "model": "gpt-4o", "api_base": "https://api.example.com/v1", "cwd": "/home/me/project", "instance_number": 1, "step_count": 4, "usage": { "input_tokens": 5321, "output_tokens": 812, "cached_tokens": 4096, "billable_tokens": 2037 }, "messages": [ { "role": "system", "content": "You are an expert planning..." }, { "role": "user", "content": "summarize this repo" }, { "role": "assistant", "content": null, "tool_calls": [ { "id": "call_1", "type": "function", "function": { "name": "execute_bash", "arguments": "{\"command\": \"ls\"}" } } ] }, { "role": "tool", "tool_call_id": "call_1", "content": "aic.py\nREADME.md" } ] } messages is the raw OpenAI message list, saved exactly as the agent holds it (same roles, tool_calls, and tool_call_ids). reason records which checkpoint produced the file (user_request, before_llm_call, assistant_message, tool_result, loop_terminated, process_exit, signal_15, interrupted, cleared, …), which makes it easy to tell where a crashed run stopped.
Because the messages array is stored verbatim, a session can be reshaped with any text editor or JSON tool:
# drop the last 6 turns, then resume python3 - <<'EOF' import json d = json.load(open(".aicsession")) d["messages"] = d["messages"][:-6] json.dump(d, open(".aicsession", "w"), indent=2) EOF python3 aic.py --api-base ... "continue from here" Change, insert, or delete turns; edits are picked up on the next startup, or immediately inside the TUI with /reload. A bare JSON array of messages is accepted in place of the full object, so you can paste a transcript straight into the file. Invalid content is repaired rather than rejected: a missing system prompt is prepended, orphan tool messages and empty assistant turns are dropped, and consecutive assistant turns are merged (keeping the text and tool calls of both). A trailing assistant answer is kept — it is the previous run's final reply. Each repair is reported so nothing changes silently. If the file ended on an assistant turn that did issue tool calls (the process died mid-command), the tool calls are answered with a [SESSION RECOVERED] notice stating the command was not re-executed — the agent is told not to assume it had any effect, rather than replaying it. Multiple instances in one directory Each process claims its session file with an flock on a sidecar .aicsession.lock (the data file itself is atomically replaced, so the lock lives beside it). Launching a second AI-Commander in the same directory warns and shifts to a numbered file instead of clobbering the first:
[SESSION] WARNING: another AI-Commander instance is already using .aicsession in this directory; this instance uses .aicsession2 instead (instance 2) Third instance → .aicsession3, and so on. The lock is released by the kernel when a process exits or dies, so a crashed run can never permanently squatter a name. --session participates in the same numbering ( 2, 3, …).
TUI agent tabs use the same scheme: every tab is an agent with its own lock, so a new tab takes the first free name (.aicsession2, …). On startup the TUI reopens a tab for every other saved session of the directory that no running agent holds, so tabs survive a restart; closing a tab deletes its session file.
At most the single in-flight turn — never earlier history — can be missing, and the only thing never replayed automatically is a shell command that had not finished when the process died.
By default, on Linux, the agent attempts to enable an OS-level Landlock sandbox using py-landlock. When active, writes are restricted to the current working directory, /tmp, /dev, and /dev/pts. The status is shown in the agent output panel (green when active, red when unsandboxed).
The sandbox is applied before the agent thread starts, so the Landlock domain covers the whole process — including every command the agent runs.
The sandbox is only applied on Linux. On other platforms (macOS, Windows) the agent runs unsandboxed and reports that status at startup.
Tip: The status bar and the startup banner show whether the sandbox is active. If you see [red]Sandbox: off[/red], either you passed --disable-sandbox, py-landlock is missing, or you are not on Linux.
--fast is designed for local inference and low-latency setups. It:
This reduces prompt size and latency at the cost of less-detailed operating instructions for the model.
Endpoints that reject stream_options or extra_body are detected and the request is retried without them automatically; the variables just skip the first attempt.
Agent commands run with PAGER=cat and GIT_PAGER=cat (a pager would wait for a keypress forever), and the output returned to the model has escape codes removed and progress-bar redraws collapsed to their final state.
├── aic.py # The entire agent (single-file implementation) ├── requirements.txt # Python dependencies ├── README.md # This file ├── changelog.txt # Release notes, newest first ├── tests/ # Test suite (truncation + core helpers) └── LICENSE # Apache 2.0 License This project is licensed under the Apache License 2.0.
ascii_pacman.py is a complete, self-contained Pac-Man game for the terminal. It uses only the Python standard library (curses + random), needs no assets, and draws everything with ASCII characters.
python3 ascii_pacman.py Key Action Arrow keys / WASD / HJKL Move P Pause / resume Q Quit R Restart after game over Eat every pellet to clear the level. Big pellets make the ghosts frightened for a few seconds — eat them for 200, 400, 800 and 1600 points in a chain. Four ghosts with classic personalities (direct chase, ambush, flanking, shy) patrol the maze, alternating between scatter and chase phases, and they get faster every level. You have three lives and the side tunnels wrap around the screen.
Options: --no-color, --seed N, --level N, --lives N, --selftest. A terminal of at least 32x23 is required.
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
None of the files in this release were uploaded with provenance metadata.
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.




